效果:
第一種實現:使用DOM
主要思路是根據實時監聽滾動條被向下拉動的距離,當其距離頂端小於某一值時使用position: fixed 固定。
核心代碼
//獲取距離頁面頂端的距離
let titleTop = tit.offsetTop;
//滾動事件
document.onscroll = function(){
//獲取當前滾動的距離
let btop = document.body.scrollTop||document.documentElement.scrollTop;
//如果滾動距離大於導航條據頂部的距離
if(titleTop - btop < 60){
//爲導航條設置fix
tit.class = "fix"; //這裏根據不同的類名設置不同的樣式
}else if (titleTop - btop > 60) {
//移除fixed
tit.class = "";
}
}
第二種 使用position:sticky
使用position:sticky只需要設置top值就可以在滾動到相應值時固定,用法簡單但要注意
其兼容性:position:sticky 這裏看到某些瀏覽器不支持此屬性值需要自己做兼容,另外chrome和safari需要是使用position:-webkit-sticky 。
粘性定位是相對於(BFC)和 最近的塊先元素定位,所以部分情況不適用