我在 javascript 中设置scrollLeft元素的属性,但是在下一行中,当我尝试取回该值时,我得到 0 作为返回。
这是由于我在可滚动元素中使用了“滚动行为:平滑”。
在 codepen 中查看:https ://codepen.io/lucaswxp/pen/VwZOZqX
或者在这里
HTML:
<div class="scrollable" id="scrollable">
<div class="large-content"></div>
</div>
<pre id="history"></pre>
JS:
const scrollable = document.getElementById('scrollable')
const history = document.getElementById('history')
scrollable.scrollLeft += 500
history.innerText += `current scrollLeft: ${scrollable.scrollLeft}` // here I get zero!!!
setTimeout(() => history.innerText += `\ncurrent scrollLeft: ${scrollable.scrollLeft}`, 1000) // after timeout, it works!
CSS
.scrollable {
width: 100%;
height: 50px;
overflow-x: auto;
scroll-behavior: smooth;
}
.large-content{
width: 30000px;
background: green;
height: 100%;
}
你可以看到只有在 setTimeout 之后我才能得到正确的值,这是因为动画结束了。如何在不计算实际值的情况下获得实际值?我不想跟踪滚动位置。