Talking about the animation example of animate of realizing jQuery by native JS

  • 2021-07-26 06:51:28
  • OfStack

This article introduces a simple talk about the native JS implementation of jQuery animate () animation example, I hope this article to help you.

Parameter description:

obj
执行动画的元素
css JSON数值对,形式为“{属性名: 属性值}",指要执行动画的书序及其对应值
interval
属性每执行1次改变的时间间隔
speedFactor 速度因子,使动画具有缓冲效果,而不是匀速不变(speedFactor为1)
func 执行完动画后的回调函数

Note:

One timer must be added for each element, otherwise it will affect each other.

cur! = css [arr] Determines whether every 1 attribute has reached the target value. The timer is cleared only if all the attributes reach the target value. The purpose of flag is to prevent the timer from being cleared if one attribute reaches the target value first but other attributes do not reach the target value. Therefore, flag is initialized to true before each change, and flag is set to false whenever one attribute that fails to reach the target is encountered, and the timer is not cleared until all attributes reach the target value.

The property value opacity has decimal values, so special handling is required: Math. ceil (speed) and Math. floor (speed) and * 100 and/100 operations.


function animate(obj, css, interval, speedFactor, func) { 
  clearInterval(obj.timer); 
  function getCss(obj, prop) { 
    if (obj.currentStyle) 
      return obj.currentStyle[prop]; // ie 
    else  
      return document.defaultView.getComputedStyle(obj, null)[prop]; //  Non ie 
  } 
  obj.timer = setInterval(function(){ 
    var flag = true; 
    for (var prop in css) { 
      var cur = 0; 
      if(prop == "opacity")  
        cur = Math.round(parseFloat(getStyle(obj, prop)) * 100); 
      else  
        cur = parseInt(getStyle(obj, prop)); 
      var speed = (css[prop] - cur) * speedFactor; 
      speed = speed > 0 ? Math.ceil(speed): Math.floor(speed); 
      if (cur != css[prop]) 
        flag = false; 
      if (prop == "opacity") { 
        obj.style.filter = "alpha(opacity : '+(cur + speed)+' )"; 
        obj.style.opacity = (cur + speed) / 100; 
} 
      else  
        obj.style[prop] = cur + speed + "px"; 
    } 
    if (flag) { 
      clearInterval(obj.timer); 
      if (func) 
        func(); 
    } 
  }, interval); 
} 
var li = document.getElementsByTagName("li"); 
for(var i = 0; i < li.length; i ++){ 
  li[i].onmouseover = function(){ 
    animate(this, {width: 100, opacity: 0.5}, 10, 0.01, function(){ 
      alert("Finished!"); 
    }); 
  } 
} 

Related articles: