使用Vue的Transition 去实现一个网站的入场动画
tips:如果你的网站还在使用普通的样式排版一点动画也没有 你就OUT了
先来看看效果:
Vue——CoderJoon
实现的逻辑
前置条件:
- vue3 创建一个小demo
以下是代码逻辑:
-
全局css处理
* { margin: 0; padding: 0; box-sizing: border-box; } body { width: 100vw; height: 100vh; padding: 20px; } #app { width: 100%; height: 100%; } .fade-enter-active, .fade-leave-active { transition: opacity 0.3s ease-in-out; } .fade-enter-from, .fade-leave-to { opacity: 0; }
-
App.vue
<template> <div class="Wrapper"> <div class="inner"> <!-- 使用transition组件实现动画效果 --> <Transition name="fade" mode="out-in"> <itemlist></itemlist> </Transition> </div> </div> </template> <script setup> import { ref } from 'vue'; import { Transition } from 'vue'; const show = ref(false); import itemlist from './components/itemlist.vue'; </script> <style scoped> .Wrapper { width: 100%; height: 100%; border-radius: 30px; display: flex; flex-direction: column; } .inner { width: 100%; height: 100%; overflow-y: auto; /* 隐藏滚动条 */ scrollbar-width: none; } .fade-enter-active, .fade-leave-active { transition: opacity 0.3s ease-in-out; } .fade-enter-from, .fade-leave-to { opacity: 0; } </style>
-
在components下面创建一个itemlist.vue
<template> <div class="ItemlistWrapper"> <template v-for="(item, index) in items"> <div class="item" :style="{ animationDelay: index / 10 + 0.2 + 's' }"> </div> </template> </div> </template> <script setup> import { ref } from 'vue' const items = ref([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]) </script> <style scoped> .ItemlistWrapper { width: 100%; height: 100%; display: flex; flex-wrap: wrap; } .item { width: 10%; height: 10%; margin-left: 1%; background-color: bisque; border: 1px solid black; box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3); border-radius: 12px; //主要的动画 opacity: 0; transform: translateY(20px); animation-timing-function: cubic-bezier(0.42, 0, 0.58, 1); animation: cardShow 0.3s forwards ease-in-out; //动画结束后元素会保持最终关键帧的样式状态(forwards)。 } @keyframes cardShow { 0% { opacity: 0; transform: translateY(20px); } 100% { opacity: 1; transform: translateY(0); } } </style>