【问题标题】:Always scroll swiper slides to top始终将滑动器幻灯片滚动到顶部
【发布时间】:2017-10-08 18:30:30
【问题描述】:

我正在使用 swiper.js。 我希望始终让新/活动幻灯片滚动到顶部,因此当新幻灯片进入视口时,内容必须滚动到顶部。

我这里有个小提琴:https://jsfiddle.net/p406sfe4/8/

我虽然这个脚本可能会完成我需要的,但它似乎不起作用:

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

谢谢!

【问题讨论】:

    标签: javascript html css swiper


    【解决方案1】:

    除非您限制容器/幻灯片的高度 - 导致溢出 - 可滚动内容实际上不会在每张幻灯片内。 在这种情况下,您应该关注 swiper 容器或其他父元素的 scrollTop 属性。

    无论您滚动到什么位置,如果将事件添加到初始化配置中,该事件将会更好地工作。要使用 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');
      }
    });
    

    【讨论】:

    • 感谢您。当你读到它的那一刻很明显,但我现在思考了 30 分钟
    【解决方案2】:

    好吧,上面的答案对我不起作用。将此答案添加到不同的场景。

    在我的情况下,我在同一页面上有多个具有不同包装器 ID 的 swiper,并且我正在参考其 ID 来初始化 Swiper,

    使用多个 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);
            );
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-08
      • 2022-11-29
      • 1970-01-01
      • 2014-02-08
      相关资源
      最近更新 更多