41
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

スクロールで特定の部分をwindowに固定する、cssとjsの書き方

Last updated at Posted at 2015-06-01

備忘録を兼ねて共有します。

方法

html

固定したい要素(以後.fixing-box)を別の要素(以後.fixing-base)で包みます。

fixing_sample.html
<div class="fixing-base">
  <div class="fixing-box">
  </div>
</div>

css

.fixing-base .fixing-box.fixedがwindowに固定される記述を追加します。

fixing_sample.css
.fixing-base .fixing-box.fixed {
  position: fixed;
  top: 0;
  z-index: 9999;
}

js

.fixing-baseより後にスクロールされた場合に下記の操作を行います。

  • .fixing-box.fixedを追加する -> 固定
  • .fixing-base.fixing-boxのmarginも含めた高さを設定する -> スクロール位置のズレ防止
  • .fixing-box.fixing-baseの幅を設定する -> .fixing-boxの見栄え調整
fixing_sample.js
function(){
  // 固定する場所が存在することの確認
  if( $('.fixing-base .fixing-box').length > 0 ){
    var baseSelector = '.fixing-base'
    var fixingSelector = baseSelector + ' .fixing-box'

    $(window).on('load scroll resize', function(){
      var baseTop = $(baseSelector).offset().top

      //固定開始位置より後にスクロールされた場合
      if( $(window).scrollTop() > baseTop ){
        $(fixingSelector).addClass('fixed')
        $(baseSelector).height($(fixingSelector).outerHeight())
        $(fixingSelector).width($(baseSelector).width())

      //固定開始位置以前にスクロールされた場合
      } else {
        $(fixingSelector).removeClass('fixed')
        $(baseSelector).height('')
        $(fixingSelector).width('')
      }
    })
  }
}

以上です。

参考

41
42
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
41
42

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?