JavaScript活动基本

在这篇文章里,我将把JS的活动由简如深的举行剖析:
## 活动基本 ##

重要步骤为:

  1. 消灭定时器,保证活动过程当中只要一个定时器

  2. 开启定时器

  3. 最先活动,同时到场推断以便在须要时住手活动。将挪动函数举行了简朴的封装。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>活动基本</title>
    <style type="text/css">
    #div1 {width: 100px;height: 100px;background: black;margin-top: 10px;position: absolute;left: 0px;}
    </style>
</head>
<body>
    <input type="button" value="move" id="btn1" />
    <div id="div1"></div>
    <script type="text/javascript">//经由过程定时器让物体动起来
    var oBtn = document.getElementById('btn1');
    var oDiv = document.getElementById('div1');
    var iTime = null;

    oBtn.onclick = function(){
        move();
    }
    function move() {
            clearInterval(iTime);//消灭定时器

        iTime = setInterval(function(){

            if (oDiv.offsetLeft == 500) {
                clearInterval(iTime);
            }else{
                oDiv.style.left = oDiv.offsetLeft+10+'px';//匀速活动
            }
        },30);
        }
    </script>
</body>
</html>

当运用这类要领时涌现的题目有:
须要相对应的盘算每次挪动的间隔,不然当挪动的间隔不能正确抵达指定位置时会涌现题目

    原文作者:做一块西瓜太郎
    原文地址: https://segmentfault.com/a/1190000006940530
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞