首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >原生JS实现各种运动之匀速运动

原生JS实现各种运动之匀速运动

作者头像
越陌度阡
发布于 2020-11-26 15:28:31
发布于 2020-11-26 15:28:31
1.8K0
举报

给大家分享一个用原生JS实现的匀速运动,效果如下:

需要注意的是,这种运动效果在实际的开发中用的比较少,用的更多的还是弹性运动和缓冲运动,以下是代码实现,欢迎大家复制粘贴及吐槽。

代码语言:javascript
复制
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现各种运动之匀速运动</title>
    <style>
        #div1 {
            width: 100px;
            height: 100px;
            position: absolute;
            background: red;
            left: 0;
            top: 50px;
        }

        span {
            width: 1px;
            height: 300px;
            background: black;
            position: absolute;
            left: 300px;
            top: 0;
        }

        ;
    </style>
    <script type="text/javascript">

        var timer = null;
        function startMove(iTarget) {

            var oDiv = document.getElementById('div1');

            clearInterval(timer);
            timer = setInterval(function () {
                var iSpeed = 0;

                if (oDiv.offsetLeft < iTarget) {

                    iSpeed = 7;

                } else {

                    iSpeed = -7;
                }
                //是否到达终点
                if (Math.abs(oDiv.offsetLeft - iTarget) < 7) {
                    //到达终点
                    clearInterval(timer);

                    oDiv.style.left = iTarget + 'px';
                } else {
                    //到达之前
                    oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px';
                }
            }, 30);
        }
    </script>
</head>

<body>
    <input type="button" value="开始运动" onclick="startMove(300)" />
    <div id="div1"></div>
    <span></span>
</body>

</html>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/17 ,如有侵权请联系 cloudcommunity@tencent.com 删除
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档