场景:一个三角形从透明到实体,持续一秒,然后匀速前进五秒,然后变大持续两秒
第一种:CSS + JS
这一种比较麻烦,而且不好控制,写起来也费劲。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 0px;
height: 0px;
background: none;
border: 50px solid red;
border-color: red transparent transparent transparent;
}
.animation1 {
animation: run 1s;
}
@keyframes run {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.animation2 {
animation: run2 5s ease;
animation-fill-mode: forwards;
}
@keyframes run2 {
0% {
transform: translateX(0px);
}
100% {
transform: translateX(100px);
}
}
.animation3 {
animation: run3 2s forwards;
}
@keyframes run3 {
0% {
width: 0px;
height: 0px;
background: none;
border: 50px solid red;
border-color: red transparent transparent transparent;
}
100% {
width: 0px;
height: 0px;
background: none;
border: 100px solid red;
border-color: red transparent transparent transparent;
transform: translateX(100px);
}
}
</style>
</head>
<body>
<div class="box animation1"></div>
<script>
let animationDiv = document.querySelector('.box');
animationDiv.addEventListener('webkitAnimationEnd', function () {
animationDiv.classList.remove('.animation1')
animationDiv.classList.add('animation2')
setTimeout(() => {
animationDiv.classList.add('animation3')
}, 5000);
})
</script>
</body>
</html>
第二种:纯 CSS
animation 不止可以写一个动画,还可以同时使用多个类名
animation: run1, run2, run3;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 0px;
height: 0px;
background: none;
border: 50px solid red;
border-color: red transparent transparent transparent;
animation: run 1s ease, run2 5s ease 1s forwards, run3 2s ease 6s forwards;
}
@keyframes run {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes run2 {
0% {
transform: translateX(0px);
}
100% {
transform: translateX(100px);
}
}
@keyframes run3 {
0% {
width: 0px;
height: 0px;
background: none;
border: 50px solid red;
border-color: red transparent transparent transparent;
}
100% {
width: 0px;
height: 0px;
background: none;
border: 100px solid red;
border-color: red transparent transparent transparent;
transform: translateX(100px);
}
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>
第二种明显比第一种更加顺滑,流畅,写起来也更舒服。