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>
  • 相关阅读:
    opencv.js小项目demo
    face-api.js 前端人脸识别,人脸检测,登录认证
    note.js 引用jQuery,
    note.js使用express创建项目的步骤以及ip和端口配置
    学习kettle遇到的问题
    Linux 后台执行python或者java代码的命令
    kettle入门大数据管理工具
    java保留2位或n位小数
    快速排序基本思想,递归写法,python和java编写快速排序
    学了一天的golang从入门到放弃
  • 原文地址:https://www.cnblogs.com/darkterror/p/6213850.html
Copyright © 2011-2022 走看看