js導航向下滾動吸附效果

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/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章