jquery 如何使滑动器的自动播放只在滑动器进入 windows 后才开始?

iecba09b  于 2023-03-01  发布在  jQuery
关注(0)|答案(5)|浏览(151)

我用这个代码来初始化滑动滑块。

var mySwiper = new Swiper ('.swiper-container', {
    // Optional parameters
    pagination: '.swiper-pagination',
    paginationClickable: true,
    nextButton: '.swiper-button-next',
    prevButton: '.swiper-button-prev',
    spaceBetween: 0,
    parallax: true,
    autoplay: 5000,
    speed: 800,
    autoplayDisableOnInteraction: false
})

由于滑块位于页面的第四部分内,并且只有在页面向下滚动后才可见,因此我希望只有在滑块进入视口后才开始自动播放。有办法做到这一点吗?

myzjeezk

myzjeezk1#

var mySwiper = new Swiper('.swiper-container', {
   autoplay: {
    delay: 5000,
  },

});
moiiocjp

moiiocjp2#

假设您正在尝试播放第四张幻灯片:

var mySwiper = new Swiper ('.swiper-container', {
    // Optional parameters
    pagination: '.swiper-pagination',
    paginationClickable: true,
    nextButton: '.swiper-button-next',
    prevButton: '.swiper-button-prev',
    spaceBetween: 0,
    parallax: true,
    autoplay: 5000,
    speed: 800,
    autoplayDisableOnInteraction: false,
    onSlideChangeStart: function(s){
      if (s.activeIndex === 3) {
          // do something here, 4th slide is active now and so on
          console.log('hi! Try to reach 4th slides');
          s.startAutoplay(); // calling autoplay on 4th slides.
      }
    }
})
kx5bkwkv

kx5bkwkv3#

您可能会使用类似jquery appear-https://github.com/morr/jquery.appear的代码

$('mySwiperContainer').on('appear', function(event, $all_appeared_elements) {
  // this element is now inside browser viewport
  var mySwiper = new Swiper ('.swiper-container', {
    // Optional parameters
    pagination: '.swiper-pagination',
    paginationClickable: true,
    nextButton: '.swiper-button-next',
    prevButton: '.swiper-button-prev',
    spaceBetween: 0,
    parallax: true,
    autoplay: 5000,
    speed: 800,
    autoplayDisableOnInteraction: false
  }) 
});
h6my8fg2

h6my8fg24#

可以使用交集观察器API使滑块仅在进入视口后自动播放。
下面是一个例子:

const swiper = new Swiper('.swiper-container', {
// Optional parameters
  autoplay: {
    delay: 3000,
  },
});

const observer = new IntersectionObserver(entries => {
  const firstEntry = entries[0];
  if (firstEntry.isIntersecting) {
    swiper.autoplay.start();
  } else {
    swiper.autoplay.stop();
  }
});

const swiperContainer = document.querySelector('.swiper-container');
observer.observe(swiperContainer);
enxuqcxy

enxuqcxy5#

需要使用带有autoplay参数的对象,或仅使用布尔值true启用默认设置以启用自动播放。以下是带有delay(转换之间,以ms为单位)参数的示例:

const swiper = new Swiper('.swiper', {
 autoplay: {
   delay: 5000,
 },
});

此处为文档参考

相关问题