简体   繁体   English

始终将 swiper 幻灯片滚动到顶部

[英]Always scroll swiper slides to top

I am using swiper.js.我正在使用 swiper.js。 I would like to always have new/active slides scroll to the top, so when a new slide enters the viewport, the content must be scrolled to the top.我希望始终将新/活动幻灯片滚动到顶部,因此当新幻灯片进入视口时,内容必须滚动到顶部。

I have a fiddle here: https://jsfiddle.net/p406sfe4/8/我在这里有一个小提琴: https : //jsfiddle.net/p406sfe4/8/

I though that this script might accomplish what I need, but it doesn't seem to work:我认为这个脚本可能会完成我所需要的,但它似乎不起作用:

swiper.on('slideChangeEnd', function(s) {
    s.slides.each(function() {
    if ($(this).index() !== s.activeIndex) $(this)[0].scrollTop = 0
   });
});

Thanks!谢谢!

Unless you're restricting the height of the container/slides - causing an overflow - the scrollable content won't actually be inside each slide.除非您限制容器/幻灯片的高度 - 导致溢出 - 可滚动内容实际上不会在每张幻灯片内。 In that case you should focus on the scrollTop property of the swiper container or other parent element.在这种情况下,您应该关注 swiper 容器或其他父元素的scrollTop属性。

Regardless of what you're scrolling to, the event will work better if added to the initialization config.不管你滚动到什么,如果添加到初始化配置中,事件会更好地工作。 To use the code from your jsfiddle:要使用 jsfiddle 中的代码:

var swiper = new Swiper('.swiper-container', {
  pagination: '.swiper-pagination',
  paginationClickable: true,
  nextButton: '.swiper-button-next',
  prevButton: '.swiper-button-prev',
  spaceBetween: 30,
  hashnav: true,
  autoHeight: true,

  // attach callback here
  onSlideChangeEnd: function (swiperObj) {
    $('.swiper-container').css('scrollTop', '0');
  }
});

Well, above answer did not work for me.好吧,以上答案对我不起作用。 Adding this answer to different scenario.将此答案添加到不同的场景。

In my case I had multiple swiper on the same page with different wrapper ID and I was initializing Swiper with reference to its ID,在我的情况下,我在同一页面上有多个具有不同包装器 ID 的 swiper,并且我正在参考其 ID 初始化 Swiper,

With multiple instances of swiper, I couldn't get to proper position of slider, so I had to it this way.使用多个 swiper 实例,我无法到达滑块的正确位置,所以我不得不这样做。

    var SwiperItems= [];
    $('.swiper-items-wrapper').each(function(i) {
        var this_ID = $(this).attr('id');
        SwiperItems[i] = new Swiper( '#' + this_ID + ' .swiper-contrainer', {
            loop: true,
            navigation: {
                nextEl: '#' + this_ID + ' .swiper-button-next-outsite',
                prevEl: '#' + this_ID + ' .swiper-button-prev-outsite',
            },
            autoHeight: true,
        });
        SwiperItems[i].on('slideChange', function (swiperObj) {
            $('html, body').animate({
                scrollTop: jQuery(SwiperItems[i].$el).offset().top
            }, 1000);
        );
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM