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