从当前位置平滑滚动元素



我编写了以下代码,将一个元素向右滚动20个像素。

const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('container').scrollLeft += 20;
};

如何使滚动平滑?我试过这样使用Element#scroll

const button = document.getElementById('slide');
button.onclick = function () {
document.getElementById('container').scroll({
left: += 20,
behavior: smooth
});
};

我能做到吗?

您可以使用Element#scrollBy从当前位置滚动一定量。

button.onclick = function () {
document.getElementById('container').scrollBy({
left: 20,
behavior: 'smooth'
});
};

这就是您想要的吗?

来自MDN:

scrollBy()滚动特定的量,而scroll()滚动到文档中的绝对位置。

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>

最新更新