1. 程式人生 > >js做固釘效果 在滾動事件繫結時碰到的坑DOMMouseScroll

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

}

}