<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="UTF-8">
<title>动画demo</title>
<link rel="stylesheet" href="demo.css">
</head>
<body>
<div id="rabbit"></div>
<script src="demo.js"></script>
</body>
</html>
/*--------------------css------------*/
#rabbit{
width:80px;
height:102px;
}
/*------js--------*/
var imgUrl ='rabbit.png';
var positions = ['0 -854','-174 -852','-349 -852','-524 -852','-698 -852','-873 -848'];
var ele = document.getElementById('rabbit');
animation(ele,positions,imgUrl);
function animation(ele,positions,imgUrl)
{
ele.style.backgroundImage = 'url('+ imgUrl + ')';
ele.style.backgroundRepeat = 'no-repeat';
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();
}
明白了这里position[0] + 'px '有空格
真的是细节很重要!!!
我的可以显示图片就是没有动画效果
代码没问题,你检查一下是不是图片路径的错误,或者是图片的文件名不对