[英]Smoothly scroll element from current position
I have written the following code to scroll an element 20 more pixels to the right.我编写了以下代码来将元素向右滚动 20 多个像素。
const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('container').scrollLeft += 20;
};
How can I make the scrolling smooth?如何使滚动平滑? I have tried using Element#scroll
like so:我试过像这样使用Element#scroll
:
const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('container').scroll({
left: += 20,
behavior: smooth
});
};
Am I able to do this?我能做到吗?
You can use Element#scrollBy
to scroll a certain amount from the current position.您可以使用Element#scrollBy
从当前 position 滚动一定量。
button.onclick = function () {
document.getElementById('container').scrollBy({
left: 20,
behavior: 'smooth'
});
};
You have a syntax problem here.你这里有语法问题。
+=
is only correct for variables, not for properties because they don't have an initial value to update. +=
仅适用于变量,不适用于属性,因为它们没有要更新的初始值。
Here is what it should look like:这是它的样子:
const button = document.getElementById('slide');
const container = document.getElementById('container')
button.onclick = function () {
container.scroll({
left: container.scrollLeft + 20,
behavior: 'smooth'
});
};
Is this what you are looking for?这是你想要的?
From MDN:来自 MDN:
scrollBy()
scrolls by a particular amount, whereasscroll()
scrolls to an absolute position in the document.scrollBy()
滚动特定的量,而scroll()
滚动到文档中的绝对 position。
https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy
const container = document.querySelector("#container"); const button = document.querySelector("#btnScroll"); button.addEventListener('click', e => { container.scrollBy({ left: 200, behavior: 'smooth' }); });
#container { position: relative; max-width: 200px; overflow-x: scroll; display: flex; margin: 20px; } img { display: inline-block }
<div id="container"> <img src="https://dummyimage.com/200x100/000/fff"> <img src="https://dummyimage.com/200x100/0f0/000"> <img src="https://dummyimage.com/200x100/00f/fff"> <img src="https://dummyimage.com/200x100/f00/fff"> </div> <button id="btnScroll">Scroll 200px</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.