bilibili上有个小小的动画,颇有趣,效果是这样的:当你把鼠标移动到一个横着的手机图案上时,这个手机图案就会立起来,动画很呆萌。我对它的实现比较好奇,因而看了一下网页代码,发现实现起来挺简单的;原来这个地方使用了一条很长的图做为背景图,原理就是经过屡次修改这个图案的style.backgroundPositionX
属性,让这个图『动起来』。html
我稍微的实现了一下,虽然不够精细,可是能看个效果git
<html> <head> <title>动画实现的一种方式</title> </head> <body> <i id = "smallTV" style="display: block; background-image: url('http://static.hdslb.com/images/base/anim-app.png'); width: 80px; height: 80px; background-position: 0px 0px; position:absolute ;cursor:pointer" onmouseover="star()" onmouseout="stop()"></i> <script> var tv = document.getElementById("smallTV"); var theWidth = 0; var changeStart, changeStop; //用于存放 setInterval() 方法 function start() { clearInterval(changeStop);//一旦鼠标移入,就中止鼠标移出时的动画 changeStart = setInterval(changeTheWidthStar,100); theWidth=0; } function stop() { clearInterval(changeStart); //一旦鼠标移开,就中止鼠标进入时的动画 changeStop = setInterval(changeTheWidthStop,100); } function changeTheWidthStart(){ theWidth -= 80; //这个数字是根据那个长长的图片来肯定的。 tv.style.backgroundPositionX = theWidth + "px"; while(theWidth <= -1280) { theWidth = -800; theWidth -= 80; tv.style.backgroundPositionX = theWidth + "px"; } } function changeTheWidthStop(){ if(theWidth< 0){ theWidth += 80; tv.style.backgroundPositionX = theWidth + "px"; } else { clearInterval(changeStop); } } </script> </body> </html>
全部的代码都在文章中写出来了,github的地址点此。github