如何在幻灯片更改时暂停YouTube视频?

时间:2019-09-16 22:35:31

标签: javascript video youtube carousel swiper

当我使用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":""}', '*');
        }
      });
    },
  });

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

1 个答案:

答案 0 :(得分:1)

您的事件看起来好像声明不正确,应该放在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":""}', '*');
        }
      });
    },
  },
});

签出API docs for events hereworking example here