TOPへ戻るボタンをつくる2
「TOPへ戻る」ボタン
- Font Awesome Iconsで設置
- 過去の記事の際のIllutratorでボタンをつくる手間がなくなります。
- jQueryで動作設定
- 初期画面ではマークがでず、ある程度スクロールするとボタンが出ます。
- SP表示でボタンが表示されます。(PC表示ではボタン非表示)
- スクロールがぬるっと動く「スムーススクロール」を設定します。
例
<PC表示>
<SP表示>
実践
<HTML>
<!doctype html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width"> <link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet"> <link href="css/style.css" rel="stylesheet"> <title>トップへ戻るボタン2</title> </head> <body> <header> <div class="container"> <h1>見出し</h1> </div><!-- container --> </header> <main> <div class="container"> </div><!-- container --> </main> <footer> <div class="container"> </div><!-- container --> </footer> <p id="to-top"><a href="#"><i class="fa fa-chevron-circle-up" aria-hidden="true"></i></a></p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script> $(function(){ var topBtn = $('#to-top'); topBtn.hide(); //スクロールが100に達したらボタン表示 $(window).scroll(function(){ if($(this).scrollTop() > 100) { topBtn.fadeIn(); } else { topBtn.fadeOut(); } }); //スムーススクロール $('a[href^="#"]').click(function(){ var speed = 500; var href= $(this).attr("href"); var target = $(href == "#" || href == "" ? 'html' : href); var position = target.offset().top; $("html, body").animate({scrollTop:position}, speed, "swing"); return false; }); }); </script> </body> </html>
<CSS>
@charset "UTF-8"; /* reset */ html,body,header,footer,div,h1 { margin: 0; padding: 0; line-height: 1.0; font-family: "Hiragino Kaku Gothic ProN", Meiryo, sans-serif; } a { text-decoration: none; color: inherit; } /* layout */ .container { width: 960px; margin: 0 auto; height: 300px;/*要素がないので高さを確保*/ } header { background: #FF0; padding: 5%; } main { background: #DDD; } footer { background: #0FF; } #to-top a { display: none; } @media screen and (max-width: 768px){ /* layout */ html { font-size: 62.5%;/* =10px */ } body { font-size: 1.6rem;/* =16px */ color: #797979; } .container { width: 100%; } /* to-top */ #to-top { position: fixed; bottom: 20px; right: 20px; } #to-top a { display: block; color: #000; background: #FFF; text-align: center; border-radius: 50%; box-sizing: border-box; } #to-top a:hover { color: #666; } .fa-chevron-circle-up { font-size: 4rem; } }
<参考サイト>