需求:頭部搜索模塊默認如下圖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>
<style rel="stylesheet" lang="css">
.no-fixed{
//這里寫默認的樣式
}
.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
}