播放YouTube视频时执行JavaScript功能(使用YouTube API)

时间:2016-10-05 15:11:24

标签: javascript jquery youtube-api youtube-javascript-api youtube-iframe-api

我正在使用以下代码在我的页面上嵌入YouTube视频:

<iframe width="400" height="300" id="newvid" src="http://www.youtube.com/embed/url?modestbranding=1&showinfo=0&feature=player_embedded&fs=0&iv_load_policy=3&rel=0" frameborder="0"></iframe>

我正在尝试使用Youtube API,因此一旦用户播放视频就会执行javascript功能,但以下代码无效,因为我在点击视频时看不到任何警告:

<script src="https://www.youtube.com/iframe_api"></script>
<script>
      var player;

      function onYouTubeIframeAPIReady() {
        player = new YT.Player('newvid', {
          events: {
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                  myFunction();
              }
            }
          }
        });
      }
</script>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>  

2 个答案:

答案 0 :(得分:1)

应使用div容器设置,而不是选择iFrame。 (这可能无法在代码段容器中正确运行,但请尝试使用代码)。

<div id="newvid"></div>

<script src="https://www.youtube.com/iframe_api"></script>
<script>
      var player;

      function onYouTubeIframeAPIReady() {
        player = new YT.Player('newvid', {
          height: '300',
          width: '400',
          videoId: 'SwxdBiazu8M', // Example video ID
          events: {
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                  myFunction();
              }
            }
          }
        });
      }
</script>

<script>
function myFunction() {
    alert("I am an alert box!");
}
</script>

答案 1 :(得分:0)

下面的代码使用JS function中的enablejsapi演示并执行iframe -

<!doctype html>
<html>
<body>
<iframe id="ytplayer" type="text/html" width="640" height="390" src="https://www.youtube.com/embed/YtF6p_w-cSc?autoplay=1&controls=0&enablejsapi=1" frameborder="0"></iframe>

<script>
  // Load the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // Replace the 'ytplayer' element with an <iframe> and
  // YouTube player after the API code downloads.
  var player;
  function onYouTubePlayerAPIReady() {  
    player = new YT.Player('ytplayer', {
      height: '390',
      width: '640',      
      events: {
            'onStateChange': function(event) {
              if (event.data == YT.PlayerState.PLAYING) {
                  myFunction();
              }
            }
          }  
    });           
  }

  function myFunction() {
    alert("I am an alert box!");
}
</script>
</body>
</html>

此处JSFiddle

根据上述代码,JS functionplayerstate后,系统会调用PLAYING。希望这对你有帮助,你也在寻找同样的东西。另外,如果您有任何问题,请告诉我。

谢谢..!