我有一个html和css滑块,我使用scroll-snap进行手动滚动,使用jQuery按钮进行自动滚动。但是,使用scroll-snap-type: x mandatory;时,jQuery scrollLeft动画会变得非常迟缓或动画消失。这种滞后是从哪里来的?是否有仅限jQuery的解决方案?
去掉css的滚动快照可以解决这个问题,但是样式对于滑块是必需的。
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
发布于 2020-03-31 03:03:05
我通过在滚动动画期间禁用scroll-snap-type属性解决了这个问题。然后在animate()回调中,我只需重新启用它。
下面是我的简化代码:
$arrows.on("click", event => {
$track.css("scroll-snap-type", "none");
$track.stop().animate(
{ scrollLeft: left },
500,
() => $track.css("scroll-snap-type", "x mandatory")
);
});发布于 2019-09-21 05:53:30
对于这个侧边滚动和捕捉问题,smooth scroll behavior polyfill提供了jQuery动画的可靠替代方案。下面是如何修改前面的示例以使用它:
$('#right, #left').click(function() {
$('.container')[0].scrollBy({
top : 0,
left : this.id == 'right' ? 300 : -300,
behavior : 'smooth'
});
});1警告:您不能控制滚动速度。然而,在我的桌面Chrome (76.0.3809.132)和移动Safari (iOS 13.0)上的测试中,它是黄油般的流畅。
发布于 2021-04-08 22:34:36
解决方案是在上使用JavaScript的原生scrollIntoView方法,您想要滚动到的元素(即滚动条中的一个框)。使用这种方法,将使用本机滚动捕捉行为(和动画),并将-如果可用- GPU加速:它将看起来平滑和本机。
在您的示例中,它将类似于:
var boxes = $(".box", ".container");
var animate_to_id = 1; //make this dynamic, based on the current active id, and where you want to scroll to.
boxes.eq(animate_to_id)[0].scrollIntoView({
behavior: 'smooth',
block: 'start',
inline: 'start'
});https://stackoverflow.com/questions/55855329
复制相似问题