【JavaScript】012.简单定时器动画

1. 效果图

在这里插入图片描述

2. 代码

图片及源码的github链接
012.定时器动画

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>012.定时器动画</title>
    <script type="text/javascript">
        window.onload = function () {
            var oDiv = document.getElementById('div1');
            var iLeft = 0;  // 左边距离
            var iMove = 20; // 移动中间量
            var iSpped = 2; // 移动速度
            var timer = setInterval(moving, 30); // 每30毫秒运行moving
            function moving(){
                // 移动到位置1000
                if(iLeft >= 1000){
                    // clearInterval(timer);  // 停止定时器
                    iMove = -iSpped;
                }
                else if(iLeft < 0){
                    // clearInterval(timer);  // 停止定时器
                    iMove = iSpped;
                }

                iLeft += iMove;  // 每次运行距离加3px
                oDiv.style.left = iLeft + 'px';
            }

        }
    </script>

    <style type="text/css">
        .box{
            width: 200px;
            height: 200px;
            background-color: gold;
            position: absolute;
            left: 0;
            top: 100px;
        }
    </style>
</head>
<body>
    <div id="div1" class="box"></div>
</body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章