![](/img/trans.png)
[英]Smoothly moving SVG element on event from current position to a given point
[英]Smoothly scroll element from current position
我編寫了以下代碼來將元素向右滾動 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
從當前 position 滾動一定量。
button.onclick = function () {
document.getElementById('container').scrollBy({
left: 20,
behavior: 'smooth'
});
};
你這里有語法問題。
+=
僅適用於變量,不適用於屬性,因為它們沒有要更新的初始值。
這是它的樣子:
const button = document.getElementById('slide');
const container = document.getElementById('container')
button.onclick = function () {
container.scroll({
left: container.scrollLeft + 20,
behavior: 'smooth'
});
};
這是你想要的?
來自 MDN:
scrollBy()
滾動特定的量,而scroll()
滾動到文檔中的絕對 position。
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.