CSS' snap-scroll'干扰jQuery' .animate scrollLeft' [英] CSS 'snap-scroll' interfering with jQuery '.animate scrollLeft'

查看:41
本文介绍了CSS' snap-scroll'干扰jQuery' .animate scrollLeft'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html和css滑块,我在其中使用 scroll-snap 进行手动滚动,并使用jQuery按钮进行自动滚动.但是,当使用 scroll-snap-type:x必选; 时,jQuery scrollLeft 动画变得非常缓慢或动画消失.滞后来自何处?是否只有jQuery解决方案?

I have an html and css slider where I'm using scroll-snap for manual scrolling and jQuery buttons for automatic scrolling. However, when using scroll-snap-type: x mandatory;, the jQuery scrollLeft animation becomes extremely laggy or the animation disappears. Where is this lag coming from? Is there a jQuery only solution?

取出css滚动快照可以解决此问题,但是样式对于滑块是必需的.

Taking out the css scroll-snap fixes the problem, but the style is necessary to the slider.

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

推荐答案

我通过在滚动动画期间禁用 scroll-snap-type 属性解决了此问题.然后在 animate()回调中,只需重新启用它即可.

I solved this issue by disabling the scroll-snap-type property during the scroll animation. Then in the animate() callback I just re-enable it.

这是我的简化代码:

$arrows.on("click", event => {
  $track.css("scroll-snap-type", "none");

  $track.stop().animate(
    { scrollLeft: left },
    500,
    () => $track.css("scroll-snap-type", "x mandatory")
  );
});

这篇关于CSS&#39; snap-scroll&amp;#39;干扰jQuery&amp;#39; .animate scrollLeft&amp;#39;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆