这个是html部分其中 isFixed的是在data中定义,初始值给个false
<div class="header " id="header" :class="== true?'isFixed':''"> <div class=" fixed-width clearfix"> <div class="header-title fl">我是顶部</div> <div class="header-buy fr" >我也是顶部</div> </div> </div>
//在methods监控滚动时间 handleScroll () { let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop; let headerTop = document.getElementById("header"); console.log(scrollTop) if (scrollTop > 140) { this.isFixed = true; } else { this.isFixed = false; } },
在mounted调用,以及在最后销毁这个方法,要不然会在别的组件也会出现这个滚动事件,会引发一些列的bug
mounted(){ window.addEventListener('scroll', this.handleScroll); }, destroyed(){ window.removeEventListener('scroll', this.handleScroll); }
这个是样式 .isFixed{ position: fixed; top: 0px; z-index: 4; width: 100%; }