JS之缓冲动画

原素材

 

main.html

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <link href="main.css" rel="stylesheet">
 5         <script type="text/javascript" src='main.js'></script>
 6             <meta charset="utf-8">
 7                 <title>
 8                     Document
 9                 </title>
10             </meta>
11         </link>
12     </head>
13     <body>
14         <div id="div1">
15         </div>
16     </body>
17 </html>

main.js

window.onload = function() {
    var odiv1 = document.getElementById('div1');//前面必须要是id的,如果为class就会报错
    odiv1.onmouseover = function() {
        startMove(700);
    };
    // odiv1.onmouseout = function() {
    //     startMove(0);
    // };
};
var timer = null;//设置一个计时器

function startMove(iTarget) {
    clearInterval(timer);//取消原有的计时器,防止叠加
    var odiv1 = document.getElementById('div1');
    timer = setInterval(function() {
        var speed = (iTarget - odiv1.offsetLeft)/20;
        speed=speed>0?Math.ceil(speed):Math.floor(speed);//取整
        if (odiv1.offsetLeft == iTarget) {
            clearInterval(timer);//当达到目标是,停止
        } else {
            odiv1.style.left = odiv1.offsetLeft + speed + 'px';
        }
    }, 30);
}

main.css

* {
    margin: 0;
    padding: 0;
}

#div1 {
    width: 480px;
    height: 120px;
    background:url(image/1.jpg) -440px -450px no-repeat;
    position: relative;//这个是运动的前提
}

 

background:url(image/1.jpg) -440px -450px no-repeat;   
若为正的则为距离左边,负的则为距图片左边440px


 

posted @ 2017-02-03 14:43  一米阳光!  阅读(257)  评论(0编辑  收藏  举报