javascript - 使用“scroll-behavior:smooth”时如何获取元素的实际scrollLeft
问题描述
我在 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 之后我才能得到正确的值,这是因为动画结束了。如何在不计算实际值的情况下获得实际值?我不想跟踪滚动位置。
解决方案
编辑:使用回调和 setInterval
<style>
.scrollable {
width: 100%;
height: 50px;
overflow-x: auto;
scroll-behavior: smooth;
}
.large-content {
width: 30000px;
background: green;
height: 100%;
}
</style>
<script>
window.onload = function () {
var scrollable = document.getElementById('scrollable');
var history = document.getElementById('history');
scroll(scrollable, 5000, function (value) {
console.log("Scroll finished (in " + value + " px)");
});
}
function scroll(elm, sl, callback) {
var finish = elm.scrollLeft + sl;
elm.scrollLeft = finish;
var cicle = setInterval(function(e = elm, c = callback) {
if (e.scrollLeft == finish) {
c(e.scrollLeft);
clearInterval(cicle);
}
}, 50);
}
</script>
<div class="scrollable" id="scrollable">
<div class="large-content"></div>
</div>
<pre id="history"></pre>
推荐阅读
- opengl - 帧缓冲区和渲染
- java - 为什么我的 print 语句在 while 循环后没有输出?
- regex - 正则表达式提取到网址的第二或第三部分
- android - 我无法从 AlarmManager 发送的 Intent 中获取额外数据
- solr - Alfresco community 6 search (Solr) does not work properly
- python - 使用tweepy收集转发者形成一组推文ID时如何设置速率限制?
- python - ModuleNotFoundError:没有名为“AppKit”的模块-Python playsound
- javascript - jquery根据条件制作if语句
- docker - 我无法访问在 docker 容器内运行的正在运行的 tomcat
- java - 在 Java 中,多个选择查询或连接,哪个是更好的做法?