react 移動端h5 監聽滾動document.documentElement.scrollTop取值總取上一次滾動觸發結束的值,也就是上一次滾動到700,這一次滾動到900,那麼在touchmove事件回調中打印出的是700
一個不夠精確的解決辦法是,爲處理邏輯增加一個定時器延時獲取,給一定的延時,可以獲得接近正確的數據,同時又能及時的觸發邏輯去渲染UI
componentDidMount() {
document.documentElement.addEventListener('touchmove', (e) => {
this.timer = setTimeout((_) => {
const postion = this.ScollPostion()
console.log('滑動距離爲:', postion)
this.setState({ scrollHeight: postion.top })
clearTimeout(this.timer)
}, 300)
})
}
ScollPostion = () => {
var 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,
}
}