需求
顶部有banner,当屏幕向上滑动超出banner高度时出现导航
思路
监听scroll,通过判断当前元素与顶部的距离,来控制导航的显隐
实现
mounted (){ // 绑定监听事件
window.addEventListener('scroll', this.handleScroll, true)
},
methods:{
handleScroll (data) { // 执行函数
let topSize=this.$refs.main_info.getBoundingClientRect().top;
if(topSize>0){
this.isShowHeader=false;
}else{
this.isShowHeader=true;
}
},
},
destroyed () { // 销毁绑定
window.removeEventListener('scroll', this.handleScroll)
}
问题总结
1、绑定的时候要加上true,需要在事件句柄在捕获阶段执行,否则监听不成功
2、因为我这里的滑动不是针对body的,所以 window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop获取的值一直为0,dom.offsetTop获取的值也是不对的,后来换成了getBoundingClientRect()这个方法解决的
dom.getBoundingClientRect()可以获取到当前元素大小及其相对于视口的高度、宽度、距离左侧、距离顶部等等数据
参考资料
https://developer.mozilla.org/zh-CN/docs/Web/API/Element/getBoundingClientRect
https://blog.csdn.net/wang1006008051/article/details/78003974
https://blog.csdn.net/qq940853667/article/details/79307453