ITの隊長のブログ

ITの隊長のブログです。Rubyを使って仕事しています。最近も色々やっているお(^ω^ = ^ω^)

fadeInとfadeOutを実装して死んだ

スポンサードリンク

ウンコード

export function fade(node, duration, _type) {
    // style属性にdisplay: noneが設定されていたとき
    console.log(node.style.display);
    if (node.style.display === 'none') {
      node.style.display = 'none';
    } else {
      node.style.display = 'block';
    }
    node.style.opacity = 0;
    if (_type === 'out') {
      node.style.opacity = 1;
    }
  
    var start = performance.now();
    let tick = function(timestamp) {
      // イージング計算式(linear)
      var easing = (timestamp - start) / duration;
      if (_type === 'out') {
        easing = 1 - easing;
      }
  
      // opacityが1を超えないように
      console.log(node.style.opacity);
      if (_type === 'in') {
        node.style.opacity = Math.min(easing, 1);
      } else {
        node.style.opacity = Math.max(easing, 0);
      }
  
      if (_type === 'in') {
        // opacityが1より小さいとき
        if (easing < 1) {
          requestAnimationFrame(tick);
          node.style.display = 'block';
        } else {
          node.style.opacity = '';
        }
      } else {
        if (easing > 0) {
          requestAnimationFrame(tick);
        } else {
          node.style.opacity = '';
          node.style.display = 'none';
        }
      }
    }
    requestAnimationFrame(tick);
  }

jQueryなら4行ぐらいでおわりなのに....