zoukankan      html  css  js  c++  java
  • JS---案例:移动元素,封装动画函数

    案例:移动元素,封装动画函数

    1. div要移动,要脱离文档流---position:absolute
    2. 如果样式的代码是在style的标签中设置,外面是获取不到
    3. 如果样式的代码是在style的属性设置,外面是可以获取
    4. 获取div的当前位置
      console.log(my$("dv").offsetLeft);

    动画函数animate封装

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
      <meta charset="UTF-8">
      <title>title</title>
      <style>
        * {
          margin: 0;
          padding: 0;
        }
    
        input {
          margin-top: 20px;
        }
    
        div {
          margin-top: 30px;
          width: 200px;
          height: 100px;
          background-color: pink;
          position: absolute;
        }
      </style>
    </head>
    
    <body>
      <input type="button" value="移动到400px" id="btn1" />
      <input type="button" value="移动到800px" id="btn2" />
      <div id="dv"></div>
      <script src="common.js"></script>
      <script>
    
        //点击第一个按钮,移动到400px
        my$("btn1").onclick = function () {
          animate(my$("dv"), 400);
        };
        //点击第二个按钮,移动到800px
        my$("btn2").onclick = function () {
          animate(my$("dv"), 800);
        };
    
        //动画函数animate封装
        function animate(element, target) {
          //先清理定时器
          clearInterval(element.timeId);
          //一会要清理定时器 (只产生一个定时器)
          element.timeId = setInterval(function () {
            //获取div当前位置
            var current = element.offsetLeft; //数字类型,没有px
            //div每移动多少像素---步数
            var step = 10;
            step = current < target ? step : -step;
            //每次移动后的距离
            current += step;
            //判断当前移动后的位置,是否达到目标位置
            if (Math.abs(target - current) > Math.abs(step)) {
              element.style.left = current + "px";
            } else {
              //清理定时器
              clearInterval(element.timeId);
              element.style.left = target + "px";
            }
          }, 20);
        }
    
      </script>
    </body>
    
    </html>
  • 相关阅读:
    典型并发任务
    第九章使用共享变量实现并发
    第八章goroutine和通道
    第七章接口
    第六章方法
    第一章
    第四章复合数据类型
    第三章基础数据类型
    Django其他
    VUE学习日记(五) ---- 组件定义 component
  • 原文地址:https://www.cnblogs.com/jane-panyiyun/p/12029759.html
Copyright © 2011-2022 走看看