用js原生实现多个属性的缓动动画函数

<script>
    //  获取当前任意一个元素的任意一个属性
    // window.getComputedStyle 火狐谷歌支持,返回值是一个字符串类型的。
    // 第一个参数是元素,第二个可以为空,返回的是属性值。
    // element.currentStyle[attr] ie支持,谷歌火狐不支持。
    function getStyle(element, attr) {
      if (window.getComputedStyle) {
        return window.getComputedStyle(element, null)[attr];
      } else {
        return element.currentStyle[attr] || 0;
      }
    }


    function animate(element, json, fn) {
      clearInterval(element.timeId);
      element.timeId = setInterval(function () {
        var flag = true;
        for (var attr in json) {
          if (attr == "opcity") {
            // opcity 的值是0-1是小数,直接计算会失去精度,可以经过计算得到最终值。
            var current = getStyle(element, attr) * 10;
            var target = json[attr] * 10;
            var step = (target - current) / 10;
            step = step > 0 ? Math.ceil(step) : Math.floor(step);
            current += step;
            //  层级改变直接改变这个属性的值
            element.style[attr] = json[attr];
          } else if (attr == "zIndex") {
            element.style[attr] = json[attr];
          } else {
            // 调用getStyle函数获取元素这个属性的当前值。
            var current = parseInt(getStyle(element, attr));
            var target = json[attr];
            var step = (target - current) / 10;
            var step = (target - current) > 0 ? Math.ceil(step) : Math.floor(step);
            current += step;
            element.style[attr] = current + "px";
          }
          if (current == target) {
            flag = false;
          }
          if (flag) {

            if (fn) {
              fn();
            }
          }
          console.log("目标" + target + ",当前" + current + ",每次移动的步数" + step);
        }
      }, 30)
    };
    document.getElementById("btn").onclick = function () {
      var json = {
        width: 400,
        height: 500,
        left: 300,
        top: 100,
        opcity: 0,
        zIndex: 10
      };
      animate(document.getElementById("dv"), json, function () {
        animate(document.getElementById("dv"), {
          width: 20,
          height: 200,
          left: 100,
          top: 0,
          opcity: 0.5
        }
        )
      })

    }
  </script>

猜你喜欢

转载自blog.csdn.net/qq_36647038/article/details/82534531