zoukankan      html  css  js  c++  java
  • 匀速运动的封装

        function animate(obj,endPosition,speed) {
            clearInterval(obj.timer);
            var speed = obj.offsetLeft > endPosition ? -speed : speed;
            obj.timer = setInterval(function () {
                var judgeDot = Math.abs(obj.offsetLeft - endPosition);
                obj.style.left = obj.offsetLeft + speed + 'px';//judgeDot changes with this interval.So this sentence should be in the interval;
                if(judgeDot <= Math.abs(speed)) {
                    clearInterval(obj.timer);
                    obj.style.left = endPosition + 'px';
                }
            },30);
        }
    //obj是将要做运动的对象,有position属性的对象,endPosition对是向右运动的最远距离时的left值,speed是运动速度。

     案例如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <style>
            #box { 100px; height: 100px; background: #dfd; position: absolute; top: 150px; left: 56px;}
        </style>
    </head>
    <body>
    <button id="b1">200</button>
    <button id="b2">400</button>
        <div id="box"></div>
    </body>
    </html>
    <script>
        var box = document.getElementById('box');
        var b1 = document.getElementById('b1');
        var b2 = document.getElementById('b2');
        b1.onclick = function () {
            animate(box,200,10);
        }
        b2.onclick = function () {
            animate(box,400,10);
        }
        function animate(obj,endPosition,speed) {
            clearInterval(obj.timer);
            var speed = obj.offsetLeft > endPosition ? -speed : speed;
            obj.timer = setInterval(function () {
                var judgeDot = Math.abs(obj.offsetLeft - endPosition);
                obj.style.left = obj.offsetLeft + speed + 'px';//judgeDot changes with this interval.So this sentence should be in the interval;
                if(judgeDot <= Math.abs(speed)) {
                    clearInterval(obj.timer);
                    obj.style.left = endPosition + 'px';
                }
            },30);
        }
    </script>
  • 相关阅读:
    Zend Guard 7 , Zend Guard Loader处理PHP加密
    [转]pHP源码加密方法调查
    使用USB Key(加密狗)实现身份认证
    4*4行列式矩阵键盘
    HDU-2546-饭卡
    HDU-2073-无限的路
    HDU-2065-"红色病毒"问题
    HDU-2063-过山车
    HDU-2060-Snooker
    HDU-2056-Rectangles
  • 原文地址:https://www.cnblogs.com/darkterror/p/6213850.html
Copyright © 2011-2022 走看看