嗨,大家好,我是镇长,lee。
又到了与大家见面的时间,今天向小伙伴们分享另一款 JavaScript 动画库 -- AutoAnimate。AutoAnimate 是一个零配置的嵌入式动画库,可添加平滑的过渡。您可以将它与 React、Solid、Vue、Svelte 或任何其他 JavaScript 应用程序一起使用。
https://github.com/formkit/auto-animate
AutoAnimate 简介
AutoAnimate 是一款无需任何配置的过渡动画库。只需使用一行代码将自动动画添加到您的 JavaScript 应用程序中。下面我们一起走入 AutoAnimate 的神秘世界吧。
安装 AutoAnimate
使用 AutoAnimate 之前,先将包引入到项目中,这次使用包管理工具进行安装。
使用 yarn
yarn add @formkit/auto-animate
使用 npm
npm install @formkit/auto-animate
基本用法
开始之前先介绍下 autoAnimate 函数,它接收执行动画的父元素。自动动画将被应用在父元素及其直接子元素上,三个阶段会自动触发动画:
- o 添加:子级元素添加到 DOM 中时
- o 删除:子级元素从 DOM 中删除时
- o 移动:子级元素在 DOM 移动时
有了上面的知识储备,下面我们开始使用 AutoAnimate 创建动画,首先创建一个原生的 JavaScript 示例。
Document
<script type="module">
import autoAnimate from './js/autoAnimate.js'
const btn = document.getElementById('button')
btn.addEventListener('click', toggle)
const dropdown = document.getElementById('dropdown')
autoAnimate(dropdown) // 调用 AutoAnimate 函数,将父元素传入
const p = document.createElement('p')
p.innerText = "我是新增的内容,使用 autoAnimate 添加过渡动画"
function toggle () {
dropdown.contains(p) ? p.remove() : dropdown.appendChild(p)
}
</script>
上面的例子,在父元素 dropdown 中插入和删除 p 标签,通过 toggle 按键切换,一个很简单的一个功能。只需一行代码 autoAnimate(dropdown) 引入 autoAnimate 函数将父元素 dropdown 传递给它,自动实现切换的过渡效果。相关如下:
进阶用法
AutoAnimate 旨在以零配置的方式使用,无需让开发人员投入过多的精力大幅度提升应用程序的用户体验。除了默认配置外,还提供了一些可选的配置项:
autoAnimate(el, {
// 动画持续时间,以毫秒为单位(默认值:250)
duration: 250,
// 运动的缓动函数(默认值:'ease-in-out')
easing: 'ease-in-out',
// 当设置为 true 时,即使用户通过 prefers-reduced-motion 表示不希望有动画,也将启用动画。
disrespectUserMotionPreference: false
})
其中包括设置动画持续时间、缓动函数以及是否忽略用户对减少动画的偏好。
AutoAnimate 支持 React、Vue、 Preact、Solid、Svelte 等框架,下面以 Vue 为例,演示如何在框架中使用。在 Vue 中支持两种使用方式:
- o 指令:v-auto-animate
- o 组合: useAutoAnimate
指令
<script setup>
import { ref } from 'vue'
const items = ref(["","","","","", ... ])
function removeItem(toRemove) {
items.value = items.value.filter((item) => item !== toRemove)
}
</script>
Click emojis to remove them.
-
{{ item }}
将指令添加到父元素上,另外 v-auto-animate 支持配置参数
组合
<script setup>
import { ref } from "vue"
import { useAutoAnimate } from "@formkit/auto-animate/vue"
const balls = ref(["red", "green", "blue"])
const [parent] = useAutoAnimate({ duration: 500 })
setInterval(() => {
balls.value.push(balls.value.shift()!)
}, 600)
</script>
-
{{ color }}
通过引入 useAutoAnimate 实现,效果如下图:
总结
通过这篇入门指南,希望你对 AutoAnimate 有了初步的了解。当你在项目中需要引入过渡动画效果时,希望能想起来它。不仅功能强大,更是开发者友好,零配置提升用户体验的绝佳神器。
更多内容请关注公众号:猿镇