首页 > Web开发 > 详细

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

时间:2015-06-22 01:06:53      阅读:324      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!