国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

JS實現(xiàn)勻速運動的代碼實例

2019-11-20 21:33:19
字體:
供稿:網(wǎng)友

效果:

 

思路:

利用setInerval()計時器,進行運動。然后關(guān)鍵的一點是在最后停止的時候給它一個填充縫隙的判斷。

代碼:

復制代碼 代碼如下:

<head runat="server">
    <title></title>
    <style type="text/css">
        #div1
        {
            width: 100px;
            height: 100px;
            background: #0000FF;
            position: absolute;
            left: 800px;
            top: 100px;
        }
        #div200
        {
            width: 1px;
            height: 400px;
            background: #FF0000;
            position: absolute;
            left: 200px;
        }
        #div500
        {
            width: 1px;
            height: 400px;
            background: #FF0000;
            position: absolute;
            left: 500px;
        }
    </style>
    <script type="text/javascript">
        function move(end) {
            var oDiv = document.getElementById('div1');
            var timer = null;
            timer = setInterval(function () {
                var speed = (end - oDiv.offsetLeft) / 5;        //根據(jù)終點和offsetLeft取出運動的速度
                speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);       //進位取整,小數(shù)位變?yōu)檎唬?BR>                //                if (oDiv.offsetLeft <= end) {
                //                    clearInterval(timer);
                //                }
                //                else {
                //                    oDiv.style.left = oDiv.offsetLeft + speed + 'px';
                //                }
                if (Math.abs(end - oDiv.offsetLeft) <= speed) { //由于在停止的時候最后會出現(xiàn)小的縫隙,或者說沒有完全的到達指定地點,所以要小于它的速度
                    clearInterval(timer);                       //當距離小于速度時,讓計時器停止
                    oDiv.style.left = end + 'px';           //在停止后填充縫隙。
                }
                else {
                    oDiv.style.left = oDiv.offsetLeft + speed + 'px';       //移動DIV
                }
            }, 30)
        }
    </script>
</head>
<body>
    <input type="button" id="btn1" value="到500的位置" onclick="move(500);" />
    <input type="button" id="btn2" value="到200的位置" onclick="move(200);" />
    <div id="div1">
    </div>
    <div id="div200">200
    </div>
    <div id="div500">500
    </div>
</body>

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 靖远县| 玛多县| 富川| 夹江县| 新绛县| 昂仁县| 卫辉市| 南开区| 德安县| 鄂尔多斯市| 如皋市| 鄂州市| 峨眉山市| 桂东县| 全南县| 海城市| 张北县| 商南县| 临澧县| 蓝山县| 岳阳县| 和田县| 平陆县| 宁武县| 延津县| 铅山县| 申扎县| 庆安县| 武清区| 深水埗区| 三江| 邻水| 浏阳市| 邹城市| 河源市| 新民市| 九寨沟县| 泾阳县| 无极县| 诸暨市| 乳山市|