当我使用swiper from iDangerous更改幻灯片时,我正在尝试暂停youtube视频

我有以enablejsapi=1结尾的youtube视频网址,这是一些代码,重要的部分是slideChange:

var swiper_video = new Swiper('.swiper-video', {

    loop: true,
    autoplay: false,
    pagination: {
      el: '.swiper-pagination',
    },
    navigation: {
      nextEl: '.swiper-button-next.video-swiper',
      prevEl: '.swiper-button-prev.video-swiper',
    },
    slideChange: function (el) {
      console.log('1');
      $('.swiper-slide').each(function () {
        var youtubePlayer = $(this).find('iframe').get(0);
        if (youtubePlayer) {
          youtubePlayer.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
        }
      });
    },
  });

似乎无法使事件触发,但我认为其余代码应能正常工作。

最佳答案

您的事件看起来好像声明不正确,应该在on:{}内,类似:

var swiper_video = new Swiper('.swiper-video', {
  on: {
    slideChange: function () {
      console.log('Hello World')
    },
  }
});

因此,使用您的完整代码:
var swiper_video = new Swiper('.swiper-video', {
  loop: true,
  autoplay: false,
  pagination: {
    el: '.swiper-pagination',
  },
  navigation: {
    nextEl: '.swiper-button-next.video-swiper',
    prevEl: '.swiper-button-prev.video-swiper',
  },
  on: {
    slideChange: function (el) {
      console.log('1');
      $('.swiper-slide').each(function () {
        var youtubePlayer = $(this).find('iframe').get(0);
        if (youtubePlayer) {
            youtubePlayer.contentWindow.postMessage('{"event":"command","func":"pauseVideo","args":""}', '*');
        }
      });
    },
  },
});

checkout API docs for events hereworking example here

关于javascript - 如何在幻灯片更改时暂停YouTube视频?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57965180/

10-10 05:59