20150908 javascript实现来回滚动的小球

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>滚动的小球</title>
<style>
*{margin:0; padding:0}
#div1{ width:200px; height:200px; background:red; border-radius:100px; position:relative;}
</style>
<script>
window.onload=function(){
    var oDiv=document.getElementById("div1"),
        flag=0;
        oDiv.onmouseover=function(){
        if(flag==0){    
            startMove(1200);
            flag=1;
        }
        else{    
            startMove(0);
            flag=0;
        }
    }
}
var timer=null;
function startMove(target){
    clearInterval(timer);
    var oDiv=document.getElementById("div1");
    timer=setInterval(function(){
        var speed=(target-oDiv.offsetLeft)/30;
        speed=speed>0?Math.ceil(speed):Math.floor(speed);
        if(oDiv.offsetLeft==target){
            clearInterval(timer);
        }else{
            oDiv.style.left=oDiv.offsetLeft+speed+"px";
        }
    },5)
}
</script>
</head>
<body>
<div id="div1">
</div>
</body>
</html>

 

posted @ 2015-09-09 06:16  Mirror1988  阅读(1318)  评论(0)    收藏  举报