如何在水平滚动时添加平滑滚动效果?

3

我刚看到了 Vlad Danila 的一个答案,但是无法重现平滑滚动效果。有人能帮我吗?

以下是我整理的一个示例代码片段:

const buttonRight = document.getElementById('slideRight');
const buttonLeft = document.getElementById('slideLeft');

buttonRight.onclick = function() {
  document.getElementById('container').scrollLeft += 20;
};
buttonLeft.onclick = function() {
  document.getElementById('container').scrollLeft -= 20;
};
#container {
  width: 145px;
  height: 100px;
  border: 1px solid #ccc;
  overflow-x: scroll;
}

#content {
  width: 250px;
  background-color: #ccc;
}
<div id="container">
  <div id="content">Click the buttons to slide horizontally!</div>
</div>
<button id="slideLeft" type="button">Slide left</button>
<button id="slideRight" type="button">Slide right</button>

谢谢您的提前帮助!
1个回答

4
您可以使用本地CSS属性scroll-behavior: smooth,如下所示:

const buttonRight = document.getElementById('slideRight'); const buttonLeft = document.getElementById('slideLeft');

buttonRight.onclick = function () {
  document.getElementById('container').scrollLeft += 20;
};
buttonLeft.onclick = function () {
  document.getElementById('container').scrollLeft -= 20;
};
#container {
  width: 145px;
  height: 100px;
  border: 1px solid #ccc;
  overflow-x: scroll;
  scroll-behavior: smooth;
}

#content {
  width: 250px;
  background-color: #ccc;
}
<div id="container">
  <div id="content">Click the buttons to slide horizontally!</div>
</div>
<button id="slideLeft" type="button">Slide left</button>
<button id="slideRight" type="button">Slide right</button>

唯一的缺点是在Safari浏览器中,它只能通过一个标志才能工作。(Ref)为了解决这个问题,您可以使用ponyfill

你好,非常感谢这个。我有点好奇怎样为这个元素添加ponyfill,如果您能告诉我就太好了,因为我在这方面是完全的新手。 :( - Saswata Baksi
它的文档非常完善。您可以使用NPM安装它,也可以将其下载到本地,然后运行'scrollIntoView()'函数。 - benhatsor

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接