【问题标题】:How to add smooth scrolling effect on horizontal scrolling?如何在水平滚动上添加平滑滚动效果?
【发布时间】:2020-12-22 17:48:40
【问题描述】:

我刚刚看到 Vlad Danila 的回答,但无法重现平滑滚动效果。谁能帮帮我?

这是我整理的示例代码 sn-p:

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>

提前致谢!

【问题讨论】:

    标签: javascript html css scroll


    【解决方案1】:

    您可以使用原生 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) 一起使用。要克服这个问题,您可以use a ponyfill

    【讨论】:

    • 你好,非常感谢,如果你能告诉我,我有点好奇如何为这个元素添加 ponyfill,因为我在这里完全是新手。 :(
    • 它是very well documented。你可以用npm安装或者下载到本地,然后运行scrollIntoView()函数。
    猜你喜欢
    • 1970-01-01
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多