您的当前位置:首页正文

Js运动动画系列1--匀速运动

2024-12-01 来源:个人技术集锦
<head>
    <title>匀速动画</title>
    <style type="text/css">
        *
        {
            margin: 0;
            padding: 0;
        }
        #div1
        {
            width: 200px;
            height: 200px;
            background: red;
            position: relative;
            left: -200px;
            top: 0;
            cursor: pointer;
        }
        #div1 span
        {
            width: 20px;
            height: 50px;
            background: blue;
            position: absolute;
            left: 200px;
            top: 75px;
        }
    </style>
</head>
<body>
    <div id="div1">
        <span id="share">分享</span>
    </div>
</body>
</html>

<script type="text/javascript">
        window.onload = function () {
            var oDiv = document.getElementById("div1");
            oDiv.onmouseover = function () {
                startMove(10,0);
            }
            oDiv.onmouseout = function () {
                startMove(-10,-200);
            }
        }
        var timer = null;
        function startMove(speed, iTarget) {//speed运动速度,iTarget目标值
            clearInterval(timer);//清楚计时器
            var oDiv = document.getElementById("div1");
            timer = setInterval(function () {//计时器
                if (oDiv.offsetLeft == iTarget) {
                    clearInterval(timer);
                } else {
                    oDiv.style.left = oDiv.offsetLeft + speed + 'px';
                }
            }, 30)
        }
    </script>

显示全文