【问题标题】:Weird scroll behavior when with chrome and smooth scrolling使用 chrome 和平滑滚动时的奇怪滚动行为
【发布时间】:2020-08-10 09:08:02
【问题描述】:

我正在编写一个虚拟滚动库并遇到一个奇怪的问题,它只出现在 chrome 中,并在 chrome 标志中禁用平滑滚动修复它。逻辑的一部分是使用不可见的 div 来拉伸容器,当滚动到顶部时,获取一些新数据然后滚动回旧顶部。但是,在平滑滚动的 chrome 中,对scrollTop 的更改似乎不会立即应用,因此会获取多个数据并且滚动位置错误。

我在 Linux 上使用 chrome 84.0.4147.105-1,并在 Windows 上进行了测试,结果相同。有时可能很难触发,最安全的方法是将滚动条拖动到顶部附近而不触发获取并向上滚动。然后你会发现控制台值从 0 跳转到 900(向下滚动)到一个小数字(为什么?)并再次触发 fetch

const container = document.getElementById('container')
const scroller = document.getElementById('scroller')

let height = 0
let isFetching = false
const fetchData = h => {
    if (isFetching) return
    isFetching = true
    setTimeout(() => {
        height += h
        scroller.style.height = height + 'px'
        container.scrollTop += h
        isFetching = false
    }, 50)
}

fetchData(800)

container.addEventListener('scroll', ev => {
    const top = ev.target.scrollTop
    console.log(top)
    if (top <= 50) {
        fetchData(800)
    }
})
#container {
    height: 200px;
    width: 500px;
    background-color: blue;
    overflow: auto;
}

#scroller {
    width: 100%;
}
<div id="container">
     <div id="scroller"></div>
</div>

【问题讨论】:

  • 这确实是一个非常丑陋的解决方案。我无法重现您看到的确切问题,但鉴于您的超时功能会反过来引发额外的滚动事件,我真的不希望它能够可靠地运行
  • 我已向chrome bugs举报

标签: javascript google-chrome scroll


【解决方案1】:

一个临时的(而且非常不雅)修复将fetchData更改为

const fetchData = h => {
    if (isFetching) return
    isFetching = true
    setTimeout(() => {
        height += h
        scroller.style.height = height + 'px'
        container.scrollTop += h
        isFetching = false
        setTimeout(() => container.scrollTop += h, 200)
    }, 50)
}

稍微延迟后再次滚动

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-28
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 2016-03-15
    相关资源
    最近更新 更多