2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【JavaScript】スクロールで要素をフェードアウトさせる

Last updated at Posted at 2020-03-16
main.js
window.onscroll = function(){
  function fadeOut(el, duration) {
    var node = document.getElementById(el);
    var start = performance.now();
    requestAnimationFrame(function tick(timestamp) {
      // イージング計算式(linear)
      var easing = (timestamp - start) / duration;
      // opacityが0か1から変数easingを引いた値をopacityに渡す
      node.style.opacity = Math.max(1 - easing, 0);
      // イージング計算式の値が1より小さいとき
      if (easing < 1) {
        requestAnimationFrame(tick);
      }
      else {
        node.style.display = 'none';
      }
    });
  }
  var scrollTop = window.pageYOffset ;
  if(scrollTop = 0) fadeOut('fadeout', 100);
}
index.html
 <div id="fadeout">フェードアウトさせる要素</div>

##解説
ページトップのときの要素を非表示にさせる処理。
requestAnimationFrameの中の処理はeasingが1より小さい値のときに、取得したDOM要素が

  • opacity:0;
  • display:none;

になる処理をする。
###timestamp
perfomance.now()よりは取得する速度は遅い。でもどうやって取得してるかがわからない。

##おわりに
逆に解説していただけたらありがたいです。一応コピペで使えます。

2
2
0

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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?