使用“滚动行为:平滑”时,如何获取元素的实际scrollLeft

时间:2019-09-27 19:23:44

标签: javascript css

我在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之后,我才能获得正确的值,这是因为动画结束了。如果不自己计算,如何获得实际价值?我不想跟踪滚动位置。

1 个答案:

答案 0 :(得分:0)

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