这个 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>