webAPI点击按钮实现物体的移动

实现的功能
1.点击按钮“移动到400px”,使div向右移动到400px的位置
2.点击按钮“移动到800px”,使div向右移动到800px的位置

静态页面

		
    <body>
    <button id="btn"> 移动到400px</button>
    <button id="btn2"> 移动到800px</button>
    <div id="dv">嗯嗯嗯</div>
    </body>

给div一点样式,便于我们观察

  <style>
        *{
            padding: 0;
            margin: 0;
        }
        #dv{
            width: 200px;
            height: 200px;
            background-color: rgb(255,255,3);
            /*透明度  区间0-1;*/
            opacity:1;
            /*opacity: absolute;*/
            position: absolute;

        }
    </style>

接下来开始写js部分
1.点击按钮使div移动到400px的位置,每过20毫秒移动10px

my$("btn").onclick=function () {
            var tim=setInterval(function () {
                //获取当前位置
                var current=my$("dv").offsetLeft;
                //2.设置div每次移动多少像素
                var step=10;
                //3.每次移动后的距离
                current+=step;
                // console.log(current);
                //4.判断当前移动后的位子是否达到目标位置
                if(current<=400){
                    //设置div的left值
                    my$("dv").style.left=current+"px";
                }
                else
                {
                    clearInterval(tim);
                }
            },20)
        }

2.点击按钮“移动到800px”,使div向右移动到800px的位置

  my$("btn2").onclick=function () {
            var tim=setInterval(function () {
                //获取当前位置
                var current=my$("dv").offsetLeft;
                //2.设置div每次移动多少像素
                var step=10;
                //3.每次移动后的距离
                current+=step;
                // console.log(current);
                //4.判断当前移动后的位子是否达到目标位置
                if(current<=800){
                    //设置div的left值
                    my$("dv").style.left=current+"px";
                }
                else
                {
                    clearInterval(tim);
                }
            },20)
        }

猜你喜欢

转载自blog.csdn.net/weixin_44392418/article/details/86491060