0
点赞
收藏
分享

微信扫一扫

js定时案例1

杰克逊爱学习 2022-02-01 阅读 67

点击按钮div进行移动,详细代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        #box1 {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
        }
    </style>
    <script>
        window.onload = function () {
            //获取box1,btn01
            var box1 = document.getElementById("box1");
            var btn01 = document.getElementById("btn01");
            //定义一个变量
            var time;
            //点击按钮box1向右移动
            btn01.onclick = function () {
                //关闭上一个定时器
                clearInterval(time);

                //开启一个定时器
                time = setInterval(function () {
                    //获取box1原来的值
                    var oldValue = parseInt(getStyle(box1, "left"));
                    //在旧值得基础上增加
                    var newValue = oldValue + 11;

                    //判断newValue是否大于800
                    if (newValue > 800) {
                        newValue = 800
                    }

                    //将新值设置为box1
                    box1.style.left = newValue + "px";

                    //当元素移动到800px时,使其停止执行移动
                    if (newValue == 800) {
                        //达到目标,关闭定时器
                        clearInterval(time);
                    }

                }, 30);

            };
        };
        /*
          定义一个函数,用来获取指定元素的当前的样式
          参数: obj:要获取样式的元素
                name:要获取的样式名   
        */
        function getStyle(obj, name) {
            if (window.getComputedStyle) {//正常浏览器有getComputedStyle这个方法,ie8以上有
                return getComputedStyle(obj, null)[name];//正常浏览器
            } else {
                return obj.currentStyle[name];//IE浏览器
            }

        }
    </script>
</head>

<body>
    <button id="btn01">点击按钮</button><br><br>
    <div id="box1"></div>
    <div style="width:0;height:1000px;border-left:1px black solid;position:absolute;left:800px;top: 0;"></div>
</body>

</html>

结果:

点击按钮后,div向右进行移动 

 

举报

相关推荐

0 条评论