gpt4 book ai didi

javascript - DOM 滚动事件的不准确性从何而来?

转载 作者:行者123 更新时间:2023-12-01 02:42:34 26 4
gpt4 key购买 nike

看看下面的代码,这里也有一个 jsbin:http://output.jsbin.com/qosevogeka/

var container = document.querySelector('.container')
var firstEventHandled = false
container.addEventListener('scroll', function(e) {
if (firstEventHandled) return
console.log(e.target.scrollLeft)
firstEventHandled = true
})
.container {
display: flex;
overflow: scroll;
}

.box {
flex-shrink: 0;
width: 40%;
height: 50px;
background: yellow;
}

.box+.box {
margin-left: 15px;
}
<body>
<div class="container">
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
<div class="box">
</div>
</div>
</body>

如果滚动结果 View ,您将看到 0 永远不会记录到我所期望的滚动中,因为 scrollLeft0在我开始滚动之前。滚动事件的这种不准确性从何而来?谢谢

最佳答案

Where does this inaccuracy with the scroll events come from? Thanks

根据 documentation

The scroll event is fired when the document view or an element has been scrolled.

所以这一行

console.log(e.target.scrollLeft)

正在记录e.target.scrollLeft滚动发生后,因为此函数是一个事件处理程序,在事件发生后执行。根据定义,一旦发生滚动,您就无法位于起点

If you scroll the resulting view, you will see that 0 is never logged to the scroll which I expect since the scrollLeft was 0 before I started scrolling

不幸的是,没有像 dragstartmousedownkeydown 那样名为 scrollstart 的事件,所以无法知道滚动何时开始,我们只知道滚动发生一次。

关于javascript - DOM 滚动事件的不准确性从何而来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47455761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com