JSFiddle - React, Tailwind, and code Playground
HTML
<div id="content">
<div id="adside">fixed</div>
</div>
CSS
#content {
position: relative;
background: u#333;
height: 3000px;
}
#adside {
position: absolute;
top: 250px;
background: #333;
width: 100%;
padding: 30px 0;
text-align: center;
color: white;
}
.follow {
position: fixed;
top: 0;
}
JavaScript
var bt = $("#adside").offset().top; // boxのページ上からの距離を取得
var ds = 0;
$(document).scroll(function(){ // スクロール発生時の処理の記述を開始
ds = $(this).scrollTop(); // ユーザのスクロールした距離を取得
if (bt <= ds) { // スクロール距離がboxの位置を超えたら、
$("#adside").addClass('follow'); // 「follow」というclassを追加する
} else if (bt >= ds) { // スクロールがページ上まで戻ったら、
$("#adside").removeClass('follow'); // classを削除
}
});