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>
  • 相关阅读:
    JavaScript自动化构建工具grunt、gulp、webpack介绍
    开始使用 Vuejs 2.0 ---简单总结2
    开始使用 Vuejs 2.0 ---简单总结1
    Bootboxjs快速制作Bootstrap的弹出框效果
    FlexSlider是一个非常出色的jQuery滑动切换插件
    CSS实现背景透明,文字不透明(兼容各浏览器)
    jquery中attr和prop的区别
    GitHub 的分支创建与合并
    [译]使用NuGet管理共享代码
    [译]Nuget.Server
  • 原文地址:https://www.cnblogs.com/darkterror/p/6213850.html
Copyright © 2011-2022 走看看