最近尝试了一下用JS实现动画效果,原理是通过改变元素background-position属性进而实现图片的动画效果
图片素材:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.rabbit{
width: 102px;
height: 66px;
border: 1px solid #ccc;
background-color: #edf3fb;
background-image: url(https://image-static.segmentfault.com/151/498/1514986056-590dbdda85b08_fix732);
background-repeat: no-repeat;
background-position: -13px 0;
}
</style>
</head>
<body>
<div class="rabbit"></div>
<script>
window.onload = function(){
/** rabbit动画**/
var positions = ["-13 0", "-128 0", "-245 0", "-360 0", "-593 0"];
var ele = document.querySelector('.rabbit');
function animation(ele,positions){
var index = 0;
function run() {
var position = positions[index].split(' ');
ele.style.backgroundPosition = position[0]+'px '+position[1]+'px';
index++;
if (index >= positions.length) {
index = 0;
}
setTimeout(run,80);
}
run();
}
animation(ele,positions);
}
</script>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。