javascript简易的动画效果

JavaScript做一个简易的动画效果,主要还是要注意的是js部分

  1. 还是和往常一样创建一个HTML,如下图(开始操作):

  1. 首先写一个div做成一个正方形盒子,内名为“box”,也可以给它写其他名,自由创作

再写两个div做成竖线,各自给一个不同的内名,在script用来做检测判断用的

还有再加两个input标签或者button标签,各给一个id名  如下图:

  1. 给这些div标签和input标签做好css属性样式,以及定好位置,如下图代码:

  1. 这就是在浏览器的一个样貌,颜色可以自己随意去改,大小也可以随意去更改,但要一致同等的高度,不然看起来很不完整

  1. 接下来的是重点,script标签,可以使用代入,也可以直接在script标签里编程,如下图的代码及一些分析,简单的没有过多的分析
  2. 源代码,下面可复制:
  • <!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>
    </head>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: pink;
            position: absolute;
            top: 100px;
            left: 0px;
        }
        .line400 {
            width: 1px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 400px;
            top: 100px;
        }
        .line800 {
            width: 1px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 800px;
            top: 100px;
        }
    </style>
    <body>
        <div id="box"></div>
        <div class="line400"></div>
        <div class="line800"></div>
    
        <input type="button" value="右移400" id="r1">
        <input type="button" value="右移800" id="r2">
    
        <script>
            var box = document.getElementById("box");//获取‘box’的id名
            var btnR1 = document.getElementById("r1");//获取‘按钮1’的id名
            var btnR2 = document.getElementById("r2");//获取‘按钮2’的id名
            btnR1.onclick = function () {
                Animation(box, 400);
            };
            btnR2.onclick = function () {
                Animation(box, 800);
            };
            // 封装动画函数
            function Animation(ele, target) {
                // 先清除动画
                clearInterval(ele.tid);
                // 获取当前位置
                var currentLeft = ele.offsetLeft;
                // 判断左移右移
                var isLeft = (currentLeft < target);
                // 开启定时器
                ele.tid = setInterval(function () {
                    // 移动
                    currentLeft = isLeft ? currentLeft + 10 : currentLeft - 10;
                    ele.style.left = currentLeft + "px";
                    // 边界检测
                    if (isLeft ? currentLeft >= target : currentLeft <= target) {
                        // 停止运动
                        clearInterval(ele.tid);
                        // 元素复位
                        ele.style.left = target + "px";
                    }
                }, 50)
            }
        </script>
    </body>
    </html>
    

版权声明:本文为Sore4原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。