您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)如何實(shí)現(xiàn)前端的吸頂效果,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
前端實(shí)現(xiàn)吸頂效果
1、監(jiān)聽scroll事件,實(shí)現(xiàn)吸頂功能
2、css實(shí)現(xiàn)吸頂
寫頁面經(jīng)常會(huì)遇到這種需求:導(dǎo)航菜單初始位置不在頭部,滑動(dòng)頁面時(shí)候當(dāng)導(dǎo)航菜單滑到頭部位置就固定在頭部,往下滑導(dǎo)航菜單又回到初始位置。
網(wǎng)頁被卷起來的高度/寬度(即瀏覽器滾動(dòng)條滾動(dòng)后隱藏的頁面內(nèi)容高度)
(javascript) document.documentElement.scrollTop //firefox (javascript) document.documentElement.scrollLeft //firefox (javascript) document.body.scrollTop //IE (javascript) document.body.scrollLeft //IE (jqurey) $(window).scrollTop() (jqurey) $(window).scrollLeft()
網(wǎng)頁工作區(qū)域的高度和寬度
(javascript) document.documentElement.clientHeight// IE firefox (jqurey) $(window).height()
元素距離文檔頂端和左邊的偏移值
(javascript) DOM元素對(duì)象.offsetTop //IE firefox (javascript) DOM元素對(duì)象.offsetLeft //IE firefox (jqurey) jq對(duì)象.offset().top (jqurey) jq對(duì)象.offset().left
獲取頁面元素距離瀏覽器工作區(qū)頂端的距離
頁面元素距離瀏覽器工作區(qū)頂端的距離 = 元素距離文檔頂端偏移值 - 網(wǎng)頁被卷起來的高度
即:
頁面元素距離瀏覽器工作區(qū)頂端的距離 = DOM元素對(duì)象.offsetTop - document.documentElement.scrollTop
1、監(jiān)聽scroll事件,實(shí)現(xiàn)吸頂功能
window.addEventListener("scroll",()=>{ let scrollTop = document.documentElement.scrollTop || document.body.scrollTop; let offsetTop = document.querySelector('#searchBar').offsetTop; if (scrollTop > offsetTop) { document.querySelector('#searchBar').style.position="fixed"; document.querySelector('#searchBar').style.top="0"; } else { document.querySelector('#searchBar').style.position=""; document.querySelector('#searchBar').style.top=""; }})
2、css實(shí)現(xiàn)吸頂
position: sticky; top:0
關(guān)于如何實(shí)現(xiàn)前端的吸頂效果就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。