实现一个可持续的动画
1、使用css动画属性
直接上代码,具体里面有注释
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS实现可持续动画</title>
<style>
.quan{
position: absolute;
width: 200px;
height: 200px;
background-color: skyblue;
animation: wei 10s ease infinite;
}
@keyframes wei{
0% {top: 0px;left: 0px;}
25% {background-color: red;top: 50px;left: 50px;}
50% {background-color: green;top: 100px;left: 100px;}
75% {background-color: blue;top: 200px;left: 200px;}
100% {background-color: black;top: 300px;left: 300px;}
}
.box1{
position: absolute;
top: 300px;
left: 100px;
width: 200px;
height: 200px;
background-color: skyblue;
animation: box1 4s ease infinite alternate;
}
@keyframes box1{
from{
}
to{
width: 400px;
height: 400px;
}
}
</style>
</head>
<body>
<div class="quan"></div>
<div class="box1"></div>
</body>
</html>
2、使用js,这里有两种方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS实现可持续的动画</title>
<style>
.quan{
width: 100px;
height: 100px;
position: absolute;
background-color: skyblue;
}
</style>
</head>
<body>
<div id="box1">点击开始动画(方式1)</div>
<div id="box2">点击开始动画(方式2)</div>
<div class="quan"></div>
<script>
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( callback ){
window.setTimeout(callback, 1000 / 60);
};
})();
let quan = document.querySelector('.quan')
let box1 = document.getElementById('box1')
let box2 = document.getElementById('box2')
let flag = true
let left=0
box1.addEventListener('click',function(){
setInterval(animation,100)
})
box2.addEventListener('click',function animloop(){
animation()
requestAnimationFrame(animloop)
})
function animation(){
left==0 ? flag=true : left==100 ? flag=false : ''
flag ? quan.style.left = `${left++}px` : quan.style.left = `${left--}px`
}
</script>
</body>
</html>
参考了网上的文档自己做的总结,有什么问题欢迎指出