LoginSignup
0
0

Vanilla Javascriptで Fade In / Out

Posted at

個人的によく使うので残しておきます。:desktop:

Javascript

Fade In 関数

引数 説明
element HTMLElement フェードインする要素
display String 要素に適用する表示スタイル。デフォルトは"block"
duration Number アニメーションの時間をミリ秒で指定
const fadeInElement = (element, display, duration) => {
  const startTime = performance.now();
  element.style.display = display || "block";

  function animate(currentTime) {
    const elapsedTime = currentTime - startTime;
    const opacity = elapsedTime / duration;
    if(opacity > 1) {
      element.style.opacity = 1;
    } else {
      element.style.opacity = opacity;
      requestAnimationFrame(animate);
    }
  }

  animate(performance.now());
};

Fade Out 関数

引数 説明
element HTMLElement フェードアウトする要素
duration Number アニメーションの時間をミリ秒で指定
const fadeOutElement = (element, duration) => {
  const startTime = performance.now();

  /**
   * 要素のOpacityを徐々に下げるアニメーション機能
   *
   * @param {DOMHighResTimeStamp} currentTime - アニメーションの現在時間
   */
  function animate(currentTime) {
    const elapsedTime = currentTime - startTime;
    const opacity = 1 - (elapsedTime / duration);

    if (opacity > 0) {
      element.style.opacity = opacity;
      requestAnimationFrame(animate);
    } else {
      element.style.display = 'none';
    }
  }
  requestAnimationFrame(animate);
};

Github

Githubにもあげてあります。(わざわざRepository作るまでもなかった:sweat_smile:

参考

Performance: now() メソッド - MDN
Window.requestAnimationFrame() - MDN

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0