vue監聽滾動事件,元素頂部吸附實現
阿新 • • 發佈:2021-01-07
需求:頭部搜尋模組預設如下圖1,但是當滾動條移動到下方看不見導航欄時,需要將搜尋模組簡化並吸附到頂部如下圖2
圖1:
圖2:
解決方案:監聽滾動事件,通過給搜尋模組頂級元素增減class來切換樣式
html和css:
<!--isFixed預設未false,如果滾動監聽觸發事件使得isFixed為true的話,就新增class is-fixed 吸附到頂部,監聽觸發為false則返回還完原來的class no-fixed-->
<div id="boxFixed" :class="[isFixed?'is-Fixed':'no-fixed']"> 這個是要滾動到頂部吸附的元素 </div>.no-fixed{ //這裡寫預設的樣式
<style rel="stylesheet"lang="css">
} .is-Fixed{ //這裡是吸附頂部的樣式 width:100%; background-color:#fff; z-index:100; position:fixed; top:0; } </style>
js方法:通過scroll監聽頁面滾動
data:function(){ return{ isFixed:false //預設為false }mounted(){ window.addEventListener('scroll',this.handleScroll) // 監聽滾動事件,然後用handleScroll這個方法進行相應的處理
},
handleScroll(){
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop // 滾動條偏移量
let offsetTop = document.querySelector('#boxFixed').offsetTop; // 要滾動到頂部吸附的元素的偏移量
this.isFixed = scrollTop > offsetTop+100 ? true : false; // 如果滾動到了預定位置,this.isFixed就為true,否則為false
}