首页 > 解决方案 > 使用“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 之后我才能得到正确的值,这是因为动画结束了。如何在不计算实际值的情况下获得实际值?我不想跟踪滚动位置。

标签: javascriptcss

解决方案


编辑:使用回调和 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>


推荐阅读