html
<div class="nav_subset" id="navSubset">
</div>
css
.nav_subset[data-fixed="fixed"]{
position: fixed;
}
.nav_subset {
position: relative;
}
js
$(function () {
let obj = document.getElementById("navSubset");
let ot = obj.offsetTop;
document.onscroll = function () {
var st = document.body.scrollTop || document.documentElement.scrollTop;
obj.setAttribute("data-fixed",st >= ot?"fixed":"")}
})
當然,還有最最最簡單的方法,那就是直接給需要添加吸附效果的元素添加position:sticky就可以啦
注意:使用position:sticky不能設置overflow:hidden
position:sticky詳細介紹參考
https://www.zhangxinxu.com/wordpress/2018/12/css-position-sticky/