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>
  • 相关阅读:
    函数指针的调用方式
    C++构造函数和析构函数顺序
    往android主项目中添加辅助项目
    Qt每次运行都是重新编译问题
    函数参数检验的研究
    动态链接库和静态链接库的区别(未完待续)
    MySQL 查看最大连接数, 当期连接数.
    Linux 命令
    Ext treelist 动态切换TreeStore
    Java 日期加减计算.
  • 原文地址:https://www.cnblogs.com/darkterror/p/6213850.html
Copyright © 2011-2022 走看看