久しぶりのjsネタ(女子小学生とは違う)
最近のWEBは縦の長さが長くなったと思いません?
パララックスとか使うと特に。
そんな時のユーザビリティに役に立つ「グローバルメニューをページ上部に固定する」jsを2パターンメモっておこうと思います。
(最近何かとよく使うのでコピペ用です)
基本のhtml部分
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div class="header"> <h1>header</h1> </div> <div class="nav"> <p>nav</p> </div> <div class="container"> <div class="section"> <p>section</p> </div> </div> <div class="footer"> <p>footer</p> </div> |
こんな感じのレイアウトを書いておきます。
今回は.navの部分を固定します。
(2パターンとも共通です)
1.普通に固定します
まずはjs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
$(function() { var $window = $(window), $container = $('.container'), $nav = $('.nav'), navH = $nav.outerHeight(), navO = $nav.offset().top, fClass = 'fixed'; $window.on('load scroll', function() { var value = $(this).scrollTop(); if ( value > navO ) { $nav.addClass(fClass); $container.css('margin-top', navH); } else { $nav.removeClass(fClass); $container.css('margin-top', '0'); } }); }); |
次にcss
1 2 3 4 5 6 |
.fixed { position: fixed; top: 0; left: 0; z-index: 1; } |
2.一旦固定してfooterが近くなると消す
まずjs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
$(function() { var $window = $(window), $container = $('.container'), $nav = $('.nav'), navH = $nav.outerHeight(), footerH = $('.footer').outerHeight(), contentH = $(document).height(), navO = $nav.offset().top, fClass = 'fixed', hClass = 'hide'; $window.on('load scroll', function() { var value = $(this).scrollTop(), scrollPos = $window.height() + value; if ( value > navO ) { if ( contentH - scrollPos <= footerH ) { $nav.addClass(hClass); } else { $nav.removeClass(hClass); } $nav.addClass(fClass); $container.css('margin-top', navH); } else { $nav.removeClass(fClass); $container.css('margin-top', '0'); } }); }); |
次にcss
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
.nav { -moz-transition: all 0.3s; -o-transition: all 0.3s; -webkit-transition: all 0.3s; transition: all 0.3s; } .fixed { position: fixed; top: 0; left: 0; z-index: 1; } .hide { -moz-transform: translateY(-100%); -ms-transform: translateY(-100%); -webkit-transform: translateY(-100%); transform: translateY(-100%); } |
とりあえずメモでした。