vue折叠展开transition动画使用keyframes实现

需求,我正常的菜单功能有隐藏与显示功能,需要增加动画

打开的时候宽度从0到300,关闭的时候,宽度从300到0

html 复制代码
<template>  
  <div id="app">  
    <button @click="toggleLength">Toggle Length</button>  
    <transition name="slide">  
      <div v-if="show" class="box"></div>  
    </transition>  
  </div>  
</template>  
  
<script>  
import { ref } from 'vue';  
  
export default {  
  setup() {  
    const show = ref(false);  
  
    const toggleLength = () => {  
      show.value = !show.value;  
    };  
  
    return {  
      show,  
      toggleLength,  
    };  
  },  
};  
</script>  
  
<style>  
#app {  
  text-align: center;  
  margin-top: 60px;  
}  
  
button {  
  padding: 10px 20px;  
}  
  
.box {  
  width: 300px;  
  height: 100px;  
  background-color: red;  
  transition: width 2s; /* 添加过渡效果 */  
}  
  
/* 使用 @keyframes 定义过渡效果 */  
@keyframes slide {  
  0% { width: 0px; } /* 打开时宽度从0开始 */  
  100% { width: 300px; } /* 打开时宽度变为300 */  
}  
@keyframes slideReverse {  
  0% { width: 300px; } /* 关闭时宽度从300开始 */  
  100% { width: 0px; } /* 关闭时宽度变为0 */  
}  
  
.slide-enter-active, .slide-leave-active {  
  animation: slide 2s forwards; /* 应用定义的动画 */  
}  
.slide-leave-active {  
  animation-direction: reverse; /* 设置动画反向播放 */  
}  
</style>
相关推荐
deli0071 小时前
MCP 协议 6 条消息拆开看:AI 为什么能自己读文件调接口
前端
风骏时光牛马1 小时前
请告诉我标题对应的内容、想要的风格,我马上给你生成。
前端
deli0071 小时前
OAuth 2.0 授权码流程实测:4 次跳转,少个 state 就被劫持
前端
deli0074 小时前
手机20%突然关机?电量百分比是估的,SOC曲线4组实测
前端
深蓝AI14 小时前
Meta 开源用了八年的设计系统 astryx:连坐两天 GitHub 总榜第一,组件库开始写给 agent 的说明书
前端·人工智能
ruanno_top14 小时前
轮播每 3 秒自己翻页:键盘停不下来,读屏也不知道换了页
vue.js
IT_陈寒15 小时前
Vue的watch把我坑惨了,原来要这样用才靠谱
前端·人工智能·后端
1-1=015 小时前
Vue 3 模板语
前端·javascript·vue.js