Js动画效果之盒子滚动(JavaScript)

  1. 效果图1:
    在这里插入图片描述

  2. 效果图2:
    在这里插入图片描述

  3. 源代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        .box1{
            /* 必须加定位才可以动 */
            position: absolute;
            left: 0;
            width: 50px;
            height: 50px;
            background-color: blueviolet;
        }
    </style>
</head>
<body>
    <div class="box1"></div>
    <script>
        // 动画原理:
        // 1.获得盒子当前位置
        // 2.让盒子在当前位置加上2px 的移动距离
        // 3.利用定时器不断重复中国操作
        // 4.接触定时器
        // 5.注意添加定位,才可以使用element.style.left
        var box1 =document.querySelector('.box1') // 获取事件源
        var timer = setInterval(function(){
           if( box1.offsetLeft >= 500){
               clearInterval(timer); // 清除定时器
           }else{
                // 每50毫秒就将新的值给box1.left
                box1.style.left  = box1.offsetLeft +2 +'px';
           }
        },50)
    </script>
</body>
</html>
  1. 喜欢的朋友记得 点赞 转发 关注噢~~~

猜你喜欢

转载自blog.csdn.net/mxjwxhn/article/details/107813919