简单的Youtube iframe API就在文档中,我做错了什么

simple Youtube iframe API right out of the documentation, what am I doing wrong?

本文关键字:什么 错了 文档 Youtube iframe API 简单      更新时间:2023-09-26

http://jsfiddle.net/y2Y5k/我正在尝试用javascript API制作一个简单的youtube播放器,但我做了一些错误的事情。

在这种情况下,我只是使用谷歌提供的文档中的确切代码片段。

我加载了api作为源代码。

我放置了一个id为"player"的div。

我做错了什么

<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
  // 2. This code loads 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);
  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      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>

这是因为Fiddle。您放入的所有JavaScript都封装在其他函数中(可能是window.onload或其他函数)。因此Youtube无法访问您的onYouTubeIframeAPIReady功能。

在Fiddle外面试试这个。它会起作用的。

在左上角,来自Frameworks&扩展,选择"无换行"而不是"onLoad"。

这会给你预期的结果。