幻想乡 - CSS
type: channel
link: https://www.nekotofu.top/index.php/tag/CSS/
items: 一个关于CSS动画的小技巧

一个关于CSS动画的小技巧
type: item
date: 2022-08-22T16:59:00+08:00
description: 某些动画有时候不需要使用JS实现，原生CSS即可。有一个元素id为 Myelement渐变动画[note-ico type="blue flat" ico=""]创建 keyframes ，设定起始颜色和终止颜色[/note-ico]@keyframes changeColor { from { color: #ff73a3; } to { color: #54ff78; } }[note-ico type="blue flat" ico=""]再从元素样式中引用，规定需要绑定到选择器的 keyframe 名称，规定完成动画所花费的时间(s/ms)，规定动画应该播放的次数，规定是否应该轮流反向播放动画。[/note-ico]#Myelement { animation: changeColor 1s infinite alternate; }效果如下：渐变动画 @keyframes changeColor { from { color: #ff73a3; } to { color: #54ff78; } } #Myelement { animation: changeColor 1s infinite alternate; } [note-ico type="blue flat" ico=""]也可以设置其他css属性的关键帧，例如字体大小，元素位置等，效果如下[/note-ico]BOX @keyframes mymove{ from{ left: 0px; } to{ left: 200px; } from{ font-size: 30px; } to{ font-size: 60px; } } #box{ font-color:white; width: 130px; height: 130px; background: red; position: relative; animation: mymove 1s infinite alternate; } [note-ico type="blue flat" ico=""]代码如下[/note-ico]@keyframes mymove{ from{ left: 0px; } to{ left: 200px; } from{ font-size: 10px; } to{ font-size: 40px; } } #box{ width: 100px; height: 100px; background: red; position: relative; animation: mymove 1s infinite alternate; }[note-ico type="blue flat" ico=""] animation 属性是一个简写属性，用于设置六个动画属性：[/note-ico]值描述animation-name规定需要绑定到选择器的 keyframe 名称animation-duration规定完成动画所花费的时间，以秒或毫秒计animation-timing-function规定动画的速度曲线animation-delay规定在动画开始之前的延迟animation-iteration-count规定动画应该播放的次数animation-direction规定是否应该轮流反向播放动画除例子中使用的参数之外，其中，也可以自定义其动画曲线 animation-timing-function 参数可选/* Keyword values */ animation-timing-function: ease; animation-timing-function: ease-in; animation-timing-function: ease-out; animation-timing-function: ease-in-out; animation-timing-function: linear; animation-timing-function: step-start; animation-timing-function: step-end; /* Function values */ animation-timing-function: cubic-bezier(0.1, 0.7, 1.0, 0.1); animation-timing-function: steps(4, end); animation-timing-function: frames(10); /* Multiple animations */ animation-timing-function: ease, step-start, cubic-bezier(0.1, 0.7, 1.0, 0.1…