【发布时间】:2019-04-25 18:11:06
【问题描述】:
我有一个 html 和 css 滑块,我使用 scroll-snap 进行手动滚动,使用 jQuery 按钮进行自动滚动。但是,当使用scroll-snap-type: x mandatory; 时,jQuery 的scrollLeft 动画会变得非常滞后或动画消失。这种滞后来自哪里?有没有 jQuery 唯一的解决方案?
取出css scroll-snap 解决了问题,但是样式对slider来说是必须的。
HTML
<div class="container">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<button id="left">←</button>
<button id="right">→</button>
CSS
.container {
max-width: 300px;
display: flex;
scroll-snap-type: x mandatory;
overflow-x: auto;
}
.box {
min-width: 100%;
min-height: 250px;
scroll-snap-align: center;
scroll-snap-stop: normal;
}
.box:nth-child(1) {background: #f55;}
.box:nth-child(2) {background: #5f5;}
.box:nth-child(3) {background: #5ff;}
jQuery
$("#right, #left").click(function() {
var dir = this.id=="right" ? '+=' : '-=' ;
$(".container").stop().animate({scrollLeft: dir+'300'}, 300);
});
这是一个活生生的例子:https://codepen.io/tystrong/pen/rboLYz
【问题讨论】:
-
如果您将
scroll-snap-type规则更改为scroll-snap-type: x proximity;或scroll-snap-type: x;(可能相同),您应该获得一些动画滚动。然而,在 Chrome 76.0.3809.132 中,动画滚动很卡/不流畅,scroll-snap-type: x mandatory;为我的模块提供了出色的用户体验。因此,我不认为这是一个可行的解决方法,但出于调查目的想提一下。