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

萨斯瓦塔·巴克西(Saswata Baksi)

我刚刚看到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>

提前致谢!

hat子

您可以使用本机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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章