JavaScript笔记53_定时器的应用(3)

两个盒子运动

<!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;
        }
        #box2{
            width: 100px;
            height: 100px;
            background-color: yellowgreen;
            position: absolute;
            top: 200px;
        }
    </style>
    <script>
        window.onload=function(){
            var btn01=document.getElementById("btn01");
            var btn02=document.getElementById("btn02");
            var btn03=document.getElementById("btn03");
            var box1=document.getElementById("box1");
            var box2=document.getElementById("box2");
            btn01.onclick=function(){
                move(box1,400,5);
            }
            btn02.onclick=function(){
                move(box1,400,-10);
            }
            btn03.onclick=function(){
                move(box2,400,10);
            }
        }; 
        //var timer;这里不能使用全局变量,因为当box1移动时,让box2移动时,box1会停止
        //box2关闭了box1的定时器
        
        //创建一个可以执行简单动画的函数
        //参数:obj 要执行动画的对象
        //speed速度
        //target
        function move(obj,target,speed){
            //关闭上一个定时器
            clearInterval(obj.timer);
            //开启定时器
            obj.timer=setInterval(function(){
                //box1.offsetLeft为数值,box1.style.left为字符串
                obj.style.left=obj.offsetLeft+speed+"px";
                //当元素移动到400px时,使其停止执行动画
                //判断box1.style.left是否大于400
                if(obj.offsetLeft>target){
                    obj.style.left=target+"px";
                }else if(obj.offsetLeft<0){
                    obj.style.left=0+"px";
                }
            }, 50);
        }
    </script>
</head>
<body>
    <button id="btn01">点击按钮以后,box1向右移动</button>
    <button id="btn02">点击按钮以后,box1向左移动</button>
    <button id="btn03">点击按钮以后,box2向右移动</button>
    <br><br><br>
    <div id="box1"></div>
    <div id="box2"></div>
    <div style="width: 0;height: 800px;border-left: 1px black solid;position: absolute;left: 400px;"></div>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值