0
1

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.

上部にfixedで固定したいとき

Posted at

ページの途中にある要素をそこまでスクロールしたらページ上部に張り付かせる。
そんな実装を求められることが時たまあります。

今までfooter側に固定はそこそこありましたがheader側に固定はあまりなかったので苦戦。
備忘録かねて記録しておきます。

もともと、ページに存在していた要素をfixedで固定しようとJavascriptからいじってましたが、こうするとfixedした瞬間に元の要素分の高さがなくなってガクっとおかしな動きをします。

そこで、固定したい要素と全く同じものを用意して、元の要素は何もいじらずに代用のものをfixedしたりnoneしたりすることでこの問題を解決します。

scrollPositionは現在のスクロール位置、fixedPositionは要素を固定したい基準のスクロール位置です。

    if (scrollPosition <= fixedPosition) {
        $('#substitute-float-top-content').css({
            display: "none",
            position: "static",
        })
    } else {
        $('#substitute-float-top-content').css({
            display: "block",
            position: "fixed",
            top: 0
        })
    }
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?