ページをスクロールしたら、ヘッダーを上部に固定したい
できればチョットだけ滑らかなアニメーションを入れたい事ってありませんか?
下記コードをコピペするだけで、簡単に実装出来ますよ。
SASSコード
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 |
header { display: flex; align-items: center; background-color: #fff; border-bottom: 1px solid #ccc; height: 10%; max-height: 80px; box-shadow: 3px 1px 1px -5px #555, 1px 1px 5px rgba(0, 0, 0, 0.1); background-color: #fff; width: 100%; transition: .3s; transform: translateY(0); &.fixed { position: fixed; top: -80px; margin: 0 auto; z-index: 100; background: rgba(255, 255, 255, 0.9); transition: .3s; transform: translateY(100%); } .is-animation { heigth: 100px; } } |
CSSコード
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 |
header { display: flex; align-items: center; background-color: #fff; border-bottom: 1px solid #ccc; height: 10%; max-height: 80px; box-shadow: 3px 1px 1px -5px #555, 1px 1px 5px rgba(0, 0, 0, 0.1); background-color: #fff; width: 100%; transition: .3s; transform: translateY(0); } header.fixed { position: fixed; top: -80px; margin: 0 auto; z-index: 100; background: rgba(255, 255, 255, 0.9); transition: .3s; transform: translateY(100%); } header .is-animation { heigth: 100px; } |
JavaScriptコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<script> (function($) { $(function() { var $win = $(window), $header = $('header'), animationClass = 'is-animation'; $win.scroll(function() { if ($(window).scrollTop() > 5) { $header.addClass('fixed'); } else { $header.removeClass('fixed'); } }); $win.on('load scroll', function() { var value = $(this).scrollTop(); if (value > 5) { $header.addClass(animationClass); } else if(value < 1) { $header.removeClass(animationClass); } }); }); })(jQuery); </script> |