【javaScript・CSS】スクロールしたときに要素を下から上に表示させる

JavaScript,css

スポンサーリンク

よく、企業のホームページなどで、スクロールをしていくと要素がひょこっと現れたりするサイトありますよね。

今回はそのやり方書きます。

[サンプル]

サンプル

[index.html]

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
    <header>
        <h1>下にスクロールしてね</h1>
    </header>
    <div class="sd sd-bu">要素1</div>
    <div class="sd sd-bu">要素2</div>
    <div class="sd sd-bu">要素3</div>
    <script src="index.js"></script>
</body>
</html>

[index.css]

/* 「header」と「div」は適当に設定 */
header {
  font-size: 40px;
  height: 100vh;
}

div {
  height: 300px;
  margin: 0 0 50px;
  background: rgb(25, 0, 255);
}

/* 以下の設定が重要 */
.sd {
  opacity: 0; /* 要素を透明にする */
  transition: all .5s ease; /* 0.5秒かけてアニメーションを行う */
}
 
.sd.show {
  opacity: 1; /* 要素を不透明する */
  transform: none; /* アニメーションをなくす */
}

.sd-bu {
  transform: translate(0, 100px); /* Y座標を100px移動するアニメーション */
}

[index.js]

var scrollDisplayElm = document.querySelectorAll('.sd');
var scrollDisplay = function () {
    for (var i = 0; i < scrollDisplayElm.length; i++) {
        var triggerMargin = 300; // 画面下部と要素の差が300pxになったらその要素にshowクラスを追加する
        if (window.innerHeight > scrollDisplayElm[i].getBoundingClientRect().top + triggerMargin) {
            scrollDisplayElm[i].classList.add('show');
        }
    }
}
// 画面が読み込まれたときのイベントを設定
window.addEventListener('load', scrollDisplay);
// スクロールされたときのイベントを設定
window.addEventListener('scroll', scrollDisplay);

JavaScript,css

Posted by ton