作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
看看下面的代码,这里也有一个 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
永远不会记录到我所期望的滚动中,因为 scrollLeft
是 0
在我开始滚动之前。滚动事件的这种不准确性从何而来?谢谢
最佳答案
Where does this inaccuracy with the scroll events come from? Thanks
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
不幸的是,没有像 dragstart
或 mousedown
或 keydown
那样名为 scrollstart 的事件,所以无法知道滚动何时开始,我们只知道滚动发生一次。
关于javascript - DOM 滚动事件的不准确性从何而来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47455761/
我是一名优秀的程序员,十分优秀!