用javascript實(shí)現(xiàn)固定側(cè)邊欄,供大家參考,具體內(nèi)容如下
正在學(xué)習(xí)大前端中,有代碼和思路不規(guī)范不正確的地方往多多包涵,感謝指教
我們?cè)诠淠衬成坛堑臅r(shí)候,或者某些網(wǎng)站的時(shí)候,通常會(huì)遇到有個(gè)東西叫做側(cè)邊欄,這個(gè)東西會(huì)跟隨我們?yōu)g覽器瀏覽長(zhǎng)度來(lái)進(jìn)行變化1,從而實(shí)現(xiàn)相對(duì)窗口的固定位置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" >頭部區(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 () { //頁(yè)面被卷去的頭部 /*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è)綠色模塊頂部距離頁(yè)面最上方的距離,然后定義cmtop這個(gè)變量,cm為側(cè)邊欄到頂部的距離,cmtop=bannerTop-cm.offsetTop。然后判斷頁(yè)面卷曲的長(zhǎng)度是否大于中間那個(gè)模塊距離頂部的距離,意思的頁(yè)面是否劃到中間這個(gè)模塊,如果劃到了中間這個(gè)模塊,那么讓側(cè)邊欄的位置固定,然后側(cè)邊欄距離頂部的距離相應(yīng)改變,這里這個(gè)情況因?yàn)閭?cè)邊欄與中間拿塊是相對(duì)靜止,所以,未卷到中間區(qū)域時(shí),cmtop的值是恒定不變的,當(dāng)卷到中間區(qū)域時(shí),banner。Top的值變?yōu)樨?fù)值,所以cmtop的值在相應(yīng)的增加,并且把這個(gè)增加的值傳給側(cè)邊欄距離頂部的值,這也就出現(xiàn)了劃到中間區(qū)域,側(cè)邊欄相對(duì)靜止的情況。如果沒(méi)有滑倒中間區(qū)域,那么側(cè)邊欄的位置還是默認(rèn)的位置。
然后如果劃到了最后一個(gè)區(qū)域則出現(xiàn)‘回到頂部'這四個(gè)字在側(cè)邊欄上。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_44029226/article/details/113738657