20-js-动画函数的封装

一、匀速动画函数的封装

    //设置任意的一个元素,移动到指定的目标位置
    function animate(element, target) {
      clearInterval(element.timeId);   //先清理定时器,这样无论怎么点击按钮都不会变快
      //定时器的id值存储到对象的一个属性中
      element.timeId = setInterval(function () {
        //获取元素的当前的位置,数字类型
        var current = element.offsetLeft;
        //每次移动的距离
        var step = 10;
        step = current < target ? step : -step;
        //当前移动到位置
        current += step;
        if (Math.abs(current - target) > Math.abs(step)) {
          element.style.left = current + "px";
        } else {
          //清理定时器
          clearInterval(element.timeId);
          //直接到达目标
          element.style.left = target + "px";
        }
      }, 20);
    }

二、变速动画函数封装
(包含多个属性,回调函数,层级,透明度)

function animate(element, json, fn) {
  clearInterval(element.timeId);//清理定时器
  //定时器,返回的是定时器的id
  element.timeId = setInterval(function () {
    var flag = true;//默认,假设,全部到达目标
    //遍历json对象中的每个属性还有属性对应的目标值
    for (var attr in json) {
      //判断这个属性attr中是不是opacity
      if (attr == "opacity") {
        //获取元素的当前的透明度,当前的透明度放大100倍
        var current = getStyle(element, attr) * 100;
        //目标的透明度放大100倍
        var target = json[attr] * 100;
        var step = (target - current) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step);
        current += step;//移动后的值
        element.style[attr] = current / 100;
      } else if (attr == "zIndex") { //判断这个属性attr中是不是zIndex
        //层级改变就是直接改变这个属性的值
        element.style[attr] = json[attr];
      } else {
        //普通的属性
        //获取元素这个属性的当前的值
        var current = parseInt(getStyle(element, attr));
        //当前的属性对应的目标值
        var target = json[attr];
        //移动的步数
        var step = (target - current) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step);
        current += step;//移动后的值
        element.style[attr] = current + "px";
      }
      //是否到达目标
      if (current != target) {
        flag = false;
      }
    }
    if (flag) {
      //清理定时器
      clearInterval(element.timeId);
      //所有的属性到达目标才能使用这个函数,前提是用户传入了这个函数
      if (fn) {
        fn();
      }
    }
    //测试代码
    console.log("目标:" + target + ",当前:" + current + ",每次的移动步数:" + step);
  }, 20);
}

你可能感兴趣的:(20-js-动画函数的封装)