javascript實(shí)現(xiàn)固定側(cè)邊欄
用javascript實(shí)現(xiàn)固定側(cè)邊欄,供大家參考,具體內(nèi)容如下
正在學(xué)習(xí)大前端中,有代碼和思路不規(guī)范不正確的地方往多多包涵,感謝指教
我們在逛某某商城的時(shí)候,或者某些網(wǎng)站的時(shí)候,通常會(huì)遇到有個(gè)東西叫做側(cè)邊欄,這個(gè)東西會(huì)跟隨我們?yōu)g覽器瀏覽長度來進(jìn)行變化1,從而實(shí)現(xiàn)相對窗口的固定位置1
**代碼如下**
<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <title>Title</title> <style> .cm{ position: absolute; top: 300px; margin-left: 1150px; width: 60px; height: 130px; background-color: pink; } .w{ margin: 10px auto; width: 80%; } .head{ height: 200px; background-color: blue; } .banner{ height: 400px; background-color: green; } .main{ height: 1000px; background-color: hotpink; } span { display: none; /*position: absolute; bottom: 0;*/ } </style></head><body> <div class='cm'> <span class='backTop'>返回頂部</span> </div> <div class='head w'>頭部區(qū)域</div> <div class='banner w'>banner區(qū)域</div> <div class='main w'>主體區(qū)域</div> <script> var cm=document.querySelector(’.cm’) var banner=document.querySelector(’.banner’) /*console.log(banner.offsetTop)*/ //被卷曲頭部的大小位置,寫在外面 var bannertop=banner.offsetTop var cmtop=cm.offsetTop-bannertop var main=document.querySelector(’.main’) var goback=document.querySelector(’.backTop’) var maintop=main.offsetTop document.addEventListener(’scroll’,function () { //頁面被卷去的頭部 /*console.log(window.pageYOffset)*/ //當(dāng)卷曲頭部大于214,側(cè)邊欄改為固定 if (window.pageYOffset>bannertop){ cm.style.position=’fixed’ cm.style.top=cmtop+’px’ }else { cm.style.position=’absolute’ cm.style.top=’300px’ } if (window.pageYOffset>maintop){ goback.style.display=’block’ }else { goback.style.display=’none’ } }) </script></body></html>
演示效果
代碼解釋
這里用到了document的添加事件scroll,瀏覽器滾動(dòng)事件,當(dāng)滾動(dòng)時(shí),觸發(fā)函數(shù)。
這里設(shè)置了一個(gè)變量為bannerTop,是中間那個(gè)綠色模塊頂部距離頁面最上方的距離,然后定義cmtop這個(gè)變量,cm為側(cè)邊欄到頂部的距離,cmtop=bannerTop-cm.offsetTop。然后判斷頁面卷曲的長度是否大于中間那個(gè)模塊距離頂部的距離,意思的頁面是否劃到中間這個(gè)模塊,如果劃到了中間這個(gè)模塊,那么讓側(cè)邊欄的位置固定,然后側(cè)邊欄距離頂部的距離相應(yīng)改變,這里這個(gè)情況因?yàn)閭?cè)邊欄與中間拿塊是相對靜止,所以,未卷到中間區(qū)域時(shí),cmtop的值是恒定不變的,當(dāng)卷到中間區(qū)域時(shí),banner。Top的值變?yōu)樨?fù)值,所以cmtop的值在相應(yīng)的增加,并且把這個(gè)增加的值傳給側(cè)邊欄距離頂部的值,這也就出現(xiàn)了劃到中間區(qū)域,側(cè)邊欄相對靜止的情況。如果沒有滑倒中間區(qū)域,那么側(cè)邊欄的位置還是默認(rèn)的位置。
然后如果劃到了最后一個(gè)區(qū)域則出現(xiàn)‘回到頂部’這四個(gè)字在側(cè)邊欄上。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. IntelliJ IDEA導(dǎo)入jar包的方法2. SSM框架JSP使用Layui實(shí)現(xiàn)layer彈出層效果3. 刪除docker里建立容器的操作方法4. IntelliJ IDEA導(dǎo)出項(xiàng)目的方法5. 解決python DataFrame 打印結(jié)果不換行問題6. Java導(dǎo)出Execl疑難點(diǎn)處理的實(shí)現(xiàn)7. Java源碼解析之ClassLoader8. JS如何在數(shù)組指定位置插入元素9. 關(guān)于IDEA git 只有Commit沒有Push的問題10. IDEA 2020 配置Tomcat服務(wù)器的詳細(xì)步驟
