訳があってposition:stickyを使えなくてjQueryで似たような挙動を実装したときの備忘録
position:stickyが使えない時
position:sticky
は親要素とかにoverflow:hidden
がかかってると効かなかったりする
Memo:position:stickyについて調べた時の備忘録
親要素にoverflowをかけざるを得なくてposition:stickyが使えないけど使いたいので実装したのが以下
position:stickyをjQueryで再現したコード
以下より必要最低限のコード
<style>
.sticky-area{
position: relative;
}
</style>
<div class="sticky-area">
<div class="sticky"></div>
</div>
<script>
jQuery(function($){
const windowHeight = $(window).height();// ウィンドウサイズを取得
const sticky = $('.sticky');// stickyさせたい要素
const targetArea = $('.sticky-area');// この要素内でstickyさせる
const stickySize = sticky.innerHeight();// stickyさせる要素の高さを取得
const stickyMargin = sticky.position().top;// 親要素の中の要素の座標を取得
const targetAreaStart = targetArea.offset().top;// stickyさせる範囲の開始の座標を取得
const stickyPos = targetAreaStart + stickyMargin;// stickyさせる要素の座標を取得
const targetAreaEnd = targetAreaStart + targetArea.innerHeight();// stickyさせる範囲の終わりの座標を取得
$(document).scroll(function() {
const currentPos = $(window).scrollTop();//現在位置の座標取得
// ↓ 現在位置がstickyさせる要素を過ぎてる
// ↓ かつ
// ↓ 現在位置がstickyさせる要素の範囲内の座標のとき
if(currentPos >= stickyPos && currentPos <= targetAreaEnd - stickySize ){
console.log("In");
sticky.css({
position:"fixed",
top:0,
bottom:"auto"
});
}else{
console.log("Out");
if(currentPos <= stickyPos ){// stickyさせる範囲の外(上部)の時
sticky.css({
position:"absolute",
top:stickyMargin,
bottom:"auto"
});
}else{// stickyさせる範囲の外(下部)の時
sticky.css({
position:"absolute",
top:"auto",
bottom:"0"
});
}
}
});
});
</script>
これでposition:sticky
と同じような動作を実装することができた
ただ、やってみて思ったのが親要素のoverflow:hidden
を外すようなコードを書いた方が絶対早い
どうしてもoverflow:hidden
が外せないんだーだけどstickyさせたいんじゃーって時にでも使ってくだせう
個人的メモ:親要素内の子要素の座標を取得するときはjqueryの
position()
メソッドを使えば行けるみたい汎用性については考えてない、とりあえず作ってみた