加速运动、减速运动、弹性运动和碰撞运动JavaScript实现

本文介绍如何使用HTML、CSS和JavaScript实现网页元素的不同动画效果,包括加速运动、减速运动、弹性运动及碰撞运动等。通过设置不同速度和方向,使得页面元素能够表现出更丰富和生动的视觉效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

html代码

<div id="box"></div>

css代码

  * {
            margin: 0;
            padding: 0;
        }

        #box {
            width: 100px;
            height: 100px;
            background: red;
            position: absolute;
        }

JS代码

加速运动

var oBox = document.getElementById("box");

    document.onclick = function () {
        var l = 0;
        setInterval(function () {
            l++;
            oBox.style.left = oBox.offsetLeft + l + 'px';
        }, 30)
    }
减速运动
 var oBox = document.getElementById("box");

    document.onclick = function () {
        var l = 30;
        setInterval(function () {
            l--;
            oBox.style.left = oBox.offsetLeft + l + 'px';
        }, 30)
    }

弹性运动

 var oBox = document.getElementById("box");
    var speed = 0;

    document.onclick = function () {
        move(oBox, 300)
    };

    function move(obj, iTarget) {
        setInterval(function () {
            speed += (iTarget - obj.offsetLeft) / 2;
            //摩擦力
            speed *= 0.8;

            oBox.style.left = oBox.offsetLeft + speed + 'px';
        }, 30)
    }

碰撞运动

 var timer = null;
    var oBox = document.getElementById("box");
    var disX = 10;
    var disY = 8;
    var iw = document.documentElement.clientWidth - oBox.offsetWidth;
    var ih = document.documentElement.clientHeight - oBox.offsetHeight;

    document.onclick = function () {
        timer = setInterval(function () {
            disY += 5;
            var l = oBox.offsetLeft + disX;
            var t = oBox.offsetTop + disY;

            if (l >= iw) {
                disX *= -0.8;
                l = iw;
            }

            if (l <= 0) {
                disX *= -0.8;
                l = 0;
            }

            if (t >= ih) {
                disY *= -0.8;
                disX *= 0.8;
                t = ih;
            }

            if (t <= 0) {
                disY *= -0.8;
                disX *= 0.8;
                t = 0;
            }

            if (Math.abs(disX) <= 1) {
                disX = 0;
            }

            //纯属碰巧
            if (Math.abs(disY) <= 2) {
                disY = 0;
            }

            if (disX == 0 && disY == 0) {
                clearInterval(timer);
            }
            console.log(disY, disX)
            oBox.style.left = l + 'px';
            oBox.style.top = t + 'px';
        }, 30)
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值