匀速运动的封装

    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 {width: 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>

 

转载于:https://www.cnblogs.com/darkterror/p/6213850.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值