Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8670

【初心者向け】jQueryで擬似的なローディングアニメーションを作る方法

$
0
0
はじめに 今回は僕が以前ウェブサイトを作る際にちょっとかっこいいローディング画面があったらなと思って作ったローディングアニメーションの作り方を解説します。 作り方 HTML まずはHTMLを用意します。 index.html <div class="loading-main"> <p>Now Loading...</p> <div class="loading-line"></div> </div> <div class="main"> <div class="center"> <div id="title"> <h1>KURO</h1> </div> </div> </div> ここで用意したのは、「Now Loading...」の文字とローディングアニメーションの線、それとローディングが終わった際に表示するタイトル画面です。(今回は自分の名前が画面中央に表示されるようにしました。) CSS 次にスタイルシートです。 loading.css * { margin: 0; padding: 0; font-family: 'Playfair Display SC', serif; } body { width: 100%; background-repeat: no-repeat; position: relative; background-color: #f9f9ff; } .loading-main { width: 350px; height: 300px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; overflow: hidden; } .loading-main p { margin: 100px; } .loading-line { height: 1.5px; background-color: #000; width: 200px; position: absolute; top: 0; bottom: 0; right: 0; left: -550px; margin: auto; } .main { display: none; overflow: hidden; position: relative; } .center { margin: auto; } #title { overflow: hidden; } #title h1 { text-align: center; margin: auto; margin-top: 350px; } CSSではloading-mainとmainの要素を真ん中に配置し、ローディングアニメーションの線がloading-mainからはみ出した際に表示させなくするようにしています。 jQuery 最後にjQueryのスクリプトを書きます。(僕の場合、他にファイルを用意せずにHTMLファイルの一番下にscriptタグで読み込ませていました。) index.html <script> $(function() { var h = $(window).height(); var w = $(window).width(); var centerW = $(window).width(); $(".loading-main").css("margin-top", h / 2 - 150 + "px"); $(".center").css("width", w / 10 * 7 + "px"); $("#title").css("height", h); var loadingAnime = setInterval(function() { $(".loading-line").animate({ "left": "500px" }, 1800).animate({ "left": "-550px" }, 0); }, 500); setTimeout(function() { $(".loading-main").animate({ "opacity": "0", }, 1000); }, 5000); setTimeout(function() { $(".loading-main").css("display", "none"); $(".main").css({ "opacity": 0, "display": "block", }); }, 6000); setTimeout(function() { $(".main").animate({ "opacity": "1", }, 1000); }, 6100); }); </script> 最初の3行は値の定義、次の3行もloading-mainやcenterの要素画面中央に寄せるためのものなのでアニメーションには直接関わってきません。 このスクリプトでは、最初の関数でsetIntervalメソッドとanimateメソッドを使いloading-line要素を左から右へ動かし、その次の関数でsetTimeoutメソッドで文字と線をフェードアウトさせています。そして最後も2番目と同様にsetTimeoutメソッドでタイトルをフェードインさせています。 setIntervalは特定のfunction内の処理を一定の間隔で繰り返すときに、setTimeoutはfunction内の処理を何秒後に実行するかを指定できます。これらは他のアニメーションを作るときにも便利です! 最後に 今回は簡単なローディングアニメーションをjQueryを使って作る方法を解説してみました。今後サイトを作る際に参考にしてみてください!

Viewing all articles
Browse latest Browse all 8670

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>