码迷,mamicode.com
首页 > 其他好文 > 详细

2016-05-30 定时器

时间:2016-05-31 00:55:27      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

1.

<body>
<input id="btn" type="button" value="按钮">
<div id="div"></div>
<script>
    var btn= document.getElementById(‘btn‘);
    var odiv=document.getElementById("div");
    //var timer=null;
    odiv.timer=null;

    btn.onclick=function(){
        clearInterval(odiv.timer);//防止动画在执行过程中,人为的在不停的点击按钮,不断产生定时器
        odiv.timer=setInterval(function(){
            var speed =getStyle(odiv,‘left‘,50);//odiv 往右移动50px
            if(speed>900){
                speed=900;
            }
            odiv.style.left=speed+‘px‘;//每隔0.1s往右移动10px
            if(speed==900){//停止移动
                clearInterval(odiv.timer);
                alert(speed);
            }
        },200);
    }

    function getStyle(obj,attr,step){//为什么要parseInt(),因为obj.currentStyle[attr] 拿到的是30px -->30
        return parseInt(obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj)[attr])+step ;
    }

</script>
</body>

 

2016-05-30 定时器

标签:

原文地址:http://www.cnblogs.com/bravolove/p/5544473.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!