youtube iframe api 没有暂停视频

youtube iframe api not pausing video

我目前正在处理一个带有滑块的页面,其中包含各种 iframe youtube 嵌入。

我试图让我的 JS 在您点击滑块上的 "next" 按钮时暂停视频。我想我已经根据 api.. 设置了所有内容。但是当您单击滑块按钮时它似乎不会暂停视频。

<script type="text/javascript">
// https://developers.google.com/youtube/iframe_api_reference

// global variable for the player
var player;

// this function gets called when API is ready to use

function onYouTubePlayerAPIReady() {
  // create the global player from the specific iframe (#video)
  player = new YT.Player('video', {
    events: {
      // call this function when player is ready to use
      'onReady': onPlayerReady
    }
  });
}

function onPlayerReady(event) {

  // bind events

  var pauseButtonRight = document.getElementByID("pause-right");
  pauseButtonRight.addEventListener("click", function() {
    player.pauseVideo();
  });
   var pauseButtonLeft = document.getElementByID("pause-left");
  pauseButtonLeft.addEventListener("click", function() {
    player.pauseVideo();
  });
}

// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
</script>

我的 iframe:

<iframe src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe>

任何方向将不胜感激。

一些事情:

  • 这是 document.getElementById 不是 document.getElementByID
  • 您实例化了 ID 为 'video' 的 Youtube 播放器,但您的 iframe 没有任何 ID :

    <iframe id="video" src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe>
    
  • 使用onYouTubeIframeAPIReady代替onYouTubePlayerAPIReady

你会得到类似的东西:

var player;

function onYouTubeIframeAPIReady() {

  // create the global player from the specific iframe (#video)
  player = new YT.Player('video', {
    events: {
      // call this function when player is ready to use
      'onReady': onPlayerReady
    }
  });
}

function onPlayerReady(event) {
  var pauseButtonRight = document.getElementById("pause");
  pauseButtonRight.addEventListener("click", function() {
    player.pauseVideo();
  });
  var pauseButtonLeft = document.getElementById("play");
  pauseButtonLeft.addEventListener("click", function() {
    player.playVideo();
  });
}

// Inject YouTube API script
var tag = document.createElement('script');
tag.src = "//www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

与:

<iframe id="video" src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe>
<input id="pause" type="submit" value="pause" />
<input id="play" type="submit" value="play" />

勾选this fiddle

勾选Youtube iframe API reference