码迷,mamicode.com
首页 > Web开发 > 详细

定时器的应用—JS学习笔记2015-6-21(第62天)

时间:2015-06-22 01:08:30      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:

定时器的管理;

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style>
#div1 { width:100px; height:100px; background:red; position:absolute; top:50px; left:30px; }
</style>
</head>

<body>

<input id="btn1" type="button" value="往后" />
<input id="btn2" type="button" value="往前" />
<div id="div1"></div>

<script>
var oBtn1 = document.getElementById(btn1);
var oBtn2 = document.getElementById(btn2);
var oDiv = document.getElementById(div1);

oBtn1.onclick = function () {
    
    clearInterval( oDiv.timer );
    
    oDiv.timer = setInterval(function () {
        
        var speed = parseInt(getStyle( oDiv, left )) + -12;            // 步长
        
        if ( speed < 10 ) {
            speed = 10;
        }
        
        oDiv.style.left = speed + px;
        
        if ( speed == 10 ) {
            clearInterval( oDiv.timer );
        }
        
    }, 30);
};

oBtn2.onclick = function () {
    
    clearInterval( oDiv.timer );
    
    oDiv.timer = setInterval(function () {
        
        var speed = parseInt(getStyle( oDiv, left )) + 12;            // 步长
        
        if ( speed > 800 ) {
            speed = 800;
        }
        
        oDiv.style.left = speed + px;
        
        if ( speed == 800 ) {
            clearInterval( oDiv.timer );
        }
        
    }, 30);
};

function getStyle ( obj, attr ) { return obj.currentStyle?obj.currentStyle[attr] : getComputedStyle( obj )[attr]; }
</script>

</body>
</html>

 

定时器的应用—JS学习笔记2015-6-21(第62天)

标签:

原文地址:http://www.cnblogs.com/zhangxg/p/4592650.html

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