CSS'snap-scroll'干扰jQuery'.animate scrollLeft'

时间:2019-04-25 18:11:07

标签: jquery html css

我有一个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">&larr;</button>
<button id="right">&rarr;</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

4 个答案:

答案 0 :(得分:3)

我通过在滚动动画期间禁用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")
  );
});

答案 1 :(得分:0)

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)的测试中,它的黄油般平滑。

答案 2 :(得分:0)

解决方案是在要滚动到的元素(即滚动条内的框之一)上使用 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'
  });

答案 3 :(得分:-1)

$("#right, #left").click(function() {
  var dir = this.id=="right" ? '+=' : '-=' ;
  $(".container").stop().animate({scrollLeft: dir+'300'},0);
});
.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;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="box"></div>
  <div class="box"></div> 
  <div class="box"></div>
</div>
<button id="left">&larr;</button> 
<button id="right">&rarr;</button>

相关问题