JSFiddle - React, Tailwind, and code Playground
HTML
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
<div class="bar">
This is the div class, top_tab_bar_bg.
</div>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
Other Content. Other Content. Other Content. Other Content. Other Content.</br>
CSS
body{
height : 1000px;
}
.bar{
width : 300px;
border-style:solid;
background-color: red;
}
JavaScript
//offset().top 是相對於文檔的偏移量,不會因為滾動卷軸而有變化。
//CSS裡的top屬性在position為fixed時,是對應到相對於所處螢幕的偏移量
//,會因滾動卷軸而有變化。
var barOffsetTop = $(".bar:not(.tempBar)").offset().top;
var barMarginTop = parseInt($(".bar:not(.tempBar)").css("margin-top"));
$(window).scroll(function() {
var scrollTopAmount= $(this).scrollTop();
//因為bar的position被設成fixed時會使下面的元素跑上來,所以做一個透明的tempBar來填充原來
//bar的位置
if (scrollTopAmount >= barOffsetTop){
//如果卷軸拉超過bar的原始offset.top(),將bar固定住
//如果沒有tempBar,做一個tempBar
if ($(".tempBar").length == 0){
$(".bar").clone().addClass('tempBar').insertAfter(".bar").css({"opacity":"0","z-index":"auto"});
}
$(".bar:not(.tempBar)").css({ "position": "fixed", "top": "-"+barMarginTop+"px" , "z-index" : "999"});
}else{
//如果卷軸拉沒有超過bar的原始offset.top(),將bar的css還原,刪除tempBar
$(".tempBar").remove();
$(".bar:not(.tempBar)").css({ "position": "static" , "z-index" : "auto"});
}
});