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>
相关推荐
深念Y5 小时前
Lenovo XiaoXinAir 14 — 性能模式切换
前端·网络
计算机魔术师5 小时前
Meta突然杀进第一梯队:一个新模型,把AI推理成本打下来8倍
前端
IT_陈寒5 小时前
Redis缓存雪崩把我坑惨了,这次长记性了
前端·人工智能·后端
风骏时光牛马6 小时前
提示词工程:大模型效能挖掘与指令设计实战
前端
仓三6 小时前
Chrome DevTools MCP 上手:让 Coding Agent 自己调试前端页面
前端·chrome devtools·mcp
计算机魔术师6 小时前
扒完Google AI Agent挑战赛的前三名,我发现了一个共同点
前端
独立开发之道6 小时前
【three.js教程】Three.js 运行时更新:矩阵、几何体、材质怎么改才不卡
javascript·矩阵·材质
不可能片场6 小时前
resources/app 为何能覆盖 app.asar
前端·electron
小婉6 小时前
我用 Next.js + React Flow 从零搭建了一个可视化 AI 工作流编排平台
前端·人工智能·node.js