繁体   English   中英

从当前 position 平滑滚动元素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM