如何在启用滚动捕捉时使用JS设置scrollLeft?

3

这个 jsFiddle 展示了一个问题。

我试图使用 scroll-snap-type 实现水平滚动的吸附效果,当用户滚动时,页面会自动吸附到最近的 div 上。

同时我也希望当用户点击按钮时,能够使 div 滚动。但是,在应用 scroll-snap-type 到容器上时,这似乎并不起作用。

如此 jsFiddle 中所示,删除 scroll-snap-type 将使按钮正常工作。而保留它会导致按钮被点击时没有任何反应。

    function myFunction() {
  const element = document.getElementById("myDIV");
  element.scrollLeft = element.scrollLeft + 50;
}

document.getElementById("button").addEventListener('click', function(){

    myFunction();

})

CSS(层叠样式表)
.x.mandatory-scroll-snapping {
  scroll-snap-type: x mandatory;
}

HTML

  <button id="button"> CLICK</button>
  <div class="container x mandatory-scroll-snapping" id="myDIV">
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
    <div>5</div>
  </div>
1个回答

2

您没有将滚动位置增加足够的量以捕捉到下一个<div>

function myFunction() {
  const element = document.getElementById("myDIV");
  element.scrollLeft = element.scrollLeft + 400;
}
document.getElementById("button").addEventListener('click', function() {
  myFunction();
})
.holster{
  height:100%;
  display:flex;
  align-items:center;
  justify-content:space-between;
  flex-flow:column nowrap;
  font-family:monospace
}
.container{
  display:flex;
  overflow:auto;
  outline:lightgray dashed 1px;
  flex:none
}
.container.x{
  width:100%;
  height:128px;
  flex-flow:row nowrap
}
.container.y{
  width:256px;
  height:256px;
  flex-flow:column nowrap
}
.x.mandatory-scroll-snapping{
  scroll-snap-type:x mandatory
}
.container>div{
  text-align:center;
  scroll-snap-align:center;
  flex:none
}
.x.container>div{
  line-height:128px;
  font-size:64px;
  width:100%;
  height:128px
}
.container>div:nth-child(2n){
  background-color:#87ea87
}
.container>div:nth-child(odd){
  background-color:#87ccea
}
<button id="button"> CLICK</button>
<div class="container x mandatory-scroll-snapping" id="myDIV">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
</div>


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