用Javascript實作固定側邊欄
正在學習大前端中,有代碼和思路不規范不正確的地方往多多包涵,感謝指教
我們在逛某某商城的時候,或者某些網站的時候,通常會遇到有個東西叫做側邊欄,這個東西會跟隨我們瀏覽器瀏覽長度來進行變化1,從而實作相對視窗的固定位置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">頭部區域</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://www.uj5u.com/qianduan/258195.html
標籤:其他
上一篇:DNA旋轉特效 html+css
下一篇:判斷JS資料型別的四種方法
