javascript實現(xiàn)固定側(cè)邊欄
用javascript實現(xiàn)固定側(cè)邊欄,供大家參考,具體內(nèi)容如下
正在學習大前端中,有代碼和思路不規(guī)范不正確的地方往多多包涵,感謝指教
我們在逛某某商城的時候,或者某些網(wǎng)站的時候,通常會遇到有個東西叫做側(cè)邊欄,這個東西會跟隨我們?yōu)g覽器瀏覽長度來進行變化1,從而實現(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)*/ //當卷曲頭部大于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,瀏覽器滾動事件,當滾動時,觸發(fā)函數(shù)。
這里設(shè)置了一個變量為bannerTop,是中間那個綠色模塊頂部距離頁面最上方的距離,然后定義cmtop這個變量,cm為側(cè)邊欄到頂部的距離,cmtop=bannerTop-cm.offsetTop。然后判斷頁面卷曲的長度是否大于中間那個模塊距離頂部的距離,意思的頁面是否劃到中間這個模塊,如果劃到了中間這個模塊,那么讓側(cè)邊欄的位置固定,然后側(cè)邊欄距離頂部的距離相應(yīng)改變,這里這個情況因為側(cè)邊欄與中間拿塊是相對靜止,所以,未卷到中間區(qū)域時,cmtop的值是恒定不變的,當卷到中間區(qū)域時,banner。Top的值變?yōu)樨撝担詂mtop的值在相應(yīng)的增加,并且把這個增加的值傳給側(cè)邊欄距離頂部的值,這也就出現(xiàn)了劃到中間區(qū)域,側(cè)邊欄相對靜止的情況。如果沒有滑倒中間區(qū)域,那么側(cè)邊欄的位置還是默認的位置。
然后如果劃到了最后一個區(qū)域則出現(xiàn)‘回到頂部’這四個字在側(cè)邊欄上。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 利用單元測試對PHP代碼進行檢查2. python如何實現(xiàn)word批量轉(zhuǎn)HTML3. python excel和yaml文件的讀取封裝4. Java8內(nèi)存模型PermGen Metaspace實例解析5. python3實現(xiàn)往mysql中插入datetime類型的數(shù)據(jù)6. moment轉(zhuǎn)化時間戳出現(xiàn)Invalid Date的問題及解決7. python爬蟲實戰(zhàn)之制作屬于自己的一個IP代理模塊8. 如何對php程序中的常見漏洞進行攻擊9. Python實現(xiàn)http接口自動化測試的示例代碼10. 利用python 下載bilibili視頻
