vue滚动

一、监听滚动事件ide

利用VUE写一个在控制台打印当前的scrollTop,this

首先,在mounted钩子中给window添加一个滚动滚动监听事件,事件

mounted () {
window.addEventListener('scroll', this.handleScroll)
},
而后在方法中,添加这个handleScroll方法rem

handleScroll () {
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
console.log(scrollTop)
},
二、监听元素到顶部的距离  并判断滚动的距离若是大于了元素到顶部的距离时,设置searchBar为true,不然就是falseit

handleScroll () {
let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
let offsetTop = document.querySelector('#searchBar').offsetTop
scrollTop > offsetTop ? this.searchBarFixed = true : this.searchBarFixed = false
},
注意,若是离开该页面须要移除这个监听的事件,否则会报错。console

destroyed () {
window.removeEventListener('scroll', this.handleScroll)
},钩子

相关文章
相关标签/搜索