<!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>動態效果</title> <style type="text/CSS"> .anim{ width :200px; height : 300px; background:url(animl1.jpg) ; background-position : 0px 0px; } </style> </head> <body> <div class="wrapper"> <div class="anim"></div> </div> </body></html>再看js:var anim = document.querySelector(".anim");var left = 0;setInterval(function(){ left +=200; if(left==1600){ left = 0; }anim.style.backgroundPosition = -left+"px 0px";},100);這就OK了! 原理在于background-position(背景圖像的起始位置)設置200px的寬度主要是因為這組每一部分寬度為200px,根據background-position的作用,在定義left的偏移量。為什么最后left前面要加上-呢?這組圖片是遞進關系,隨著往右的偏移,背景圖片在向左遞減。比如background-position:200px 0px;它是以容器的左上角為參考,向左偏移200px,也就成為這樣:第一幅圖就向左偏移200px,消失在顯示范圍內了。然后當它為-1600px時,到達最后一幅圖,把left設置0,又重新開始。再根據setInterval()方法,無限循環,就得到了gif動態效果。
新聞熱點
疑難解答