YouTube iframe自定义控制菜单暂停功能

时间:2012-11-20 15:47:52

标签: javascript jquery api iframe youtube

我想创建一个可以使用iFrame API控制YouTube视频的菜单。 我在HTML中放了一个id =“pause_button”的按钮,并尝试使用jquery创建一个函数,以便在单击时暂停视频。以下是我的HTML文档:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">

  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');
  tag.src = "//www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.paresntNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }

</script>
<script type="text/javascript">
$(document).ready(function(){
    $("#pause_button").click(function(){
        $("#test").append("TEST");
        player.pauseVideo();
    });
});
</script>

</head>
  <body>
    <!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
    <iframe id="player" type="text/html" width="640" height="390" src="http://www.youtube.com/embed/u1zgFlCw8Aw?enablejsapi=1&origin=http://example.com" frameborder="0">
    </iframe>

    <button id="pause_button">STOP</button>
    <div id="test">TEST<br /></div>
  </body>
</html>

1 个答案:

答案 0 :(得分:1)

您的第一个错误,即无法调用未定义的方法'insertBefore',是由于代码中的拼写错误;应该是:

firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

(你有paresntNode。)

第二个错误是由于您在iframe网址的参数上的来源;您离开示例源(http://example.com),但应将其设置为运行代码的服务器的值。这是一种安全措施,允许您的脚本随后与播放器的方法进行交互。