用javascript實現固定側邊欄,供大家參考,具體內容如下
正在學習大前端中,有代碼和思路不規范不正確的地方往多多包涵,感謝指教
我們在逛某某商城的時候,或者某些網站的時候,通常會遇到有個東西叫做側邊欄,這個東西會跟隨我們瀏覽器瀏覽長度來進行變化1,從而實現相對窗口的固定位置1
**代碼如下**
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
<!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" >頭部區域</ div > < div class = "banner w" >banner區域</ div > < div class = "main w" >主體區域</ 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,側邊欄改為固定 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,瀏覽器滾動事件,當滾動時,觸發函數。
這里設置了一個變量為bannerTop,是中間那個綠色模塊頂部距離頁面最上方的距離,然后定義cmtop這個變量,cm為側邊欄到頂部的距離,cmtop=bannerTop-cm.offsetTop。然后判斷頁面卷曲的長度是否大于中間那個模塊距離頂部的距離,意思的頁面是否劃到中間這個模塊,如果劃到了中間這個模塊,那么讓側邊欄的位置固定,然后側邊欄距離頂部的距離相應改變,這里這個情況因為側邊欄與中間拿塊是相對靜止,所以,未卷到中間區域時,cmtop的值是恒定不變的,當卷到中間區域時,banner。Top的值變為負值,所以cmtop的值在相應的增加,并且把這個增加的值傳給側邊欄距離頂部的值,這也就出現了劃到中間區域,側邊欄相對靜止的情況。如果沒有滑倒中間區域,那么側邊欄的位置還是默認的位置。
然后如果劃到了最后一個區域則出現‘回到頂部'這四個字在側邊欄上。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/weixin_44029226/article/details/113738657