js做固钉效果 在滚动事件绑定时碰到的坑DOMMouseScroll

在使用vue做 “固钉” 效果时,碰到了以下巨坑

我是这样子绑定滚动监听事件的:

if (document.addEventListener) {

document.addEventListener('DOMMouseScroll', this.onScroll, false)

} // W3C

window.onmousewheel = document.onmousewheel = this.onScroll

console.log('绑定在DOMMouseScroll上导致的坑', document.documentElement.scrollHeight, document.documentElement.scrollTop, document.documentElement.clientHeight)  // 打印结果,当用户操作滚动条的时候会出现当前获取到的值是上一次的值(document.documentElement.scrollTop),这就导致了滚动始终会出现差一截px的现象,并且当用户手动拉动滚动条时,不触发滚动事件!!!

解决:

if (document.addEventListener) {

document.addEventListener('scroll', this.onScroll, false)

} // W3C

window.onmousewheel = document.onmousewheel = this.onScroll

我有以下2个方法处理滚动:

onScroll (e) {

e = e || window.event

let header = document.querySelector('.header')

let position = this.ScollPostion()

this.position = position

if (position.top === 0) {

header.style.boxShadow = '0 0 0 0 rgba(0, 0, 0, 0.5)'

} else {

header.style.boxShadow = '0 2px 50px 0 rgba(0, 0, 0, 0.5)'

}

},

ScollPostion () {

let t, l, w, h

if (document.documentElement && document.documentElement.scrollTop) {

t = document.documentElement.scrollTop

l = document.documentElement.scrollLeft

w = document.documentElement.scrollWidth

h = document.documentElement.scrollHeight

} else if (document.body) {

t = document.body.scrollTop

l = document.body.scrollLeft

w = document.body.scrollWidth

h = document.body.scrollHeight

}

return {

top: t,

left: l,

width: w,

height: h

}

}

猜你喜欢

转载自blog.csdn.net/hzxOnlineOk/article/details/85330055