【jQuery】ふわっと要素を出現させる方法
結論
まずは、ふわっと出現させたい要素に対して、fadeinというクラスを付けます。
<p class="fadein"></p>
.fadein { // 透明度は0 opacity: 0; // 下に50px下がった状態 transform: translate(0, 50px); }
次に、スクロールイベントを追加します。
$(window).scroll(function(){ // fadeinというクラスを持つ要素それぞれに対して $('.fadein').each(function(){ // 今から変数を定義する。windowHeightには、画面の高さ(初期値) var windowHeight = $(window).height(), // scrollには、スクロールした量 scroll = $(window).scrollTop(), // elemYには、要素のY座標を代入する。以上で変数の定義は終わり。 elemY = $(this).offset().top; // もし、「画面の高さ(初期値) + スクロールした量 - 調整値(100)」が要素のY座標より大きければ if (windowHeight + scroll - 100 > elemY){ // このクラスに、scrollinというクラスを追加する $(this).addClass('scrollin'); } }); });
.scrollin { //透明度は1 opacity: 1; //通常の位置 transform: translate(0, 0); //全てのプロパティに対して、3秒で transition: all 3s; }
完成サンプル
http://xs437226.xsrv.jp/sample/scroll-fadein/
ソースコード
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="reset.css"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src="query.js"></script> </head> <body> <section class="first-view"> <p>Scroll</p> </section> <section class="second-view"> <p class="fadein"></p> </section> <section class="third-view"> <p class="fadein"></p> </section> </body> </html>
SCSS
@mixin layout { display: flex; justify-content: center; align-items: center; height: 100vh; } @mixin box { height: 300px; width: 300px; line-height: 300px; text-align: center; } .fadein { opacity: 0; transform: translate(0, 50px); } .scrollin { opacity: 1; transform: translate(0, 0); transition: all 3s; } .first-view { @include layout; P { font-size: 50px; position: relative; &::after { position: absolute; bottom: -20px; margin: auto; left: 0; right: 0; content: "↓"; height: 10px; width: 30px; font-size: 30px; } } } .second-view { @include layout; align-items: flex-start; p { background-color: #ea5550; border-radius: 10px; @include box; } } .third-view { @include layout; align-items: flex-start; p { background-color: #00a1e9; border-radius: 50%; @include box; } }
jQuery
$(function(){ $(window).scroll(function (){ $('.fadein').each(function(){ var windowHeight = $(window).height(), scroll = $(window).scrollTop(), elemY = $(this).offset().top; if (windowHeight + scroll - 100 > elemY){ $(this).addClass('scrollin'); } }); }); });