LoginSignup
23
21

More than 5 years have passed since last update.

スクロールするとヘッダーがふわっと固定されるパターン

Last updated at Posted at 2016-07-02

網元公式サイトでも実装してるヘッダーのとこね。
https://ja.amimoto-ami.com/

仕様

  1. HTMLはワンソース
  2. スクロールしたらヘッダーは常に上部に固定

デモ

ソース

  • JavaScript(jQuery) はスクロール量を判定して対象の DOM に CSS クラスを付与(削除)するだけ
  • CSS で .scrolled の見た目作っておく
  • .scrolled 有り・無し間のアニメーションは transition 使う
masthead-scroll.js
(function($) {
    $(window).on('load resize', function(){
        // masthead scroll
        var header   = $('#header-nav'); // fixed DOM
        var addclass = 'scrolled'; // add css class
        var offset   = header.offset();
        var scrollY  = offset.top; // scroll

        $(window).scroll(function() {
        if ($(window).scrollTop() > scrollY) {
            header.addClass(addclass);
        } else {
            header.removeClass(addclass);
        }
    });
})(jQuery);

.scrolled の見た目はお好みで。
(デモの方はもうちょっと細かく指定している)

masthead.css

#masthead {
  padding: 15px;
  background: white;
  -webkit-transition: all 0.3s;
     -moz-transition: all 0.3s;
      -ms-transition: all 0.3s;
       -o-transition: all 0.3s;
          transition: all 0.3s;
}

#masthead.scrolled {
  color: white;
  background: rgba(0, 0, 0, 0.8);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
  width: 100%;
}

IE9? 知らない子ですね。
(クラスは付与されるので、transitionが無効=ふわっとならないだけ)

23
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
21