Youtube API全屏问题

时间:2015-04-14 19:54:08

标签: javascript api youtube

我正在开发一个RSS新闻阅读器项目:http://davidcool.com/feeds

我有这个代码来处理嵌入youtube HTML播放器:

 /*!
 * Finds all youtube embeds and creates thumbnail + play button
 */

// Find all the YouTube video embedded on a page
var videos = document.getElementsByClassName("youtube"); 

for (var i=0; i<videos.length; i++) {

  var youtube = videos[i];

  // Based on the YouTube ID, we can easily find the thumbnail image
  var img = document.createElement("img");

  img.setAttribute("class", "item-thumb");
  img.setAttribute("src", "http://i.ytimg.com/vi/" + youtube.id + "/hqdefault.jpg");

  // Overlay the Play icon to make it look like a video player
  var playIcon = document.createElement("img");

  playIcon.setAttribute("class","item-play");
  playIcon.setAttribute("src", "play.png");   

  youtube.appendChild(img);
  youtube.appendChild(playIcon);

  // Attach an onclick event to the YouTube Thumbnail
  youtube.onclick = function() {

  // Create an iFrame with autoplay set to true
  var iframe = document.createElement("iframe");
  iframe.setAttribute("id",this.id);
  iframe.setAttribute('allowfullscreen','1');
  iframe.setAttribute('frameborder','0')
  iframe.setAttribute("src", "http://www.youtube.com/embed/" + this.id + "?autoplay=1&autohide=1&border=0&vq=hd720&modestbranding=1&wmode=opaque&enablejsapi=1&origin=http://davidcool.com");

  // The height and width of the iFrame should be the same as parent
  iframe.style.width  = this.style.width;
  iframe.style.height = this.style.height;

  // Replace the YouTube thumbnail with YouTube HTML5 Player
  this.parentNode.replaceChild(iframe, this);

  if (iframe.requestFullscreen) {
    iframe.requestFullscreen();
  }
  else if (iframe.msRequestFullscreen) {
    iframe.msRequestFullscreen();
  }
  else if (iframe.mozRequestFullScreen) {
    iframe.mozRequestFullScreen();
  }
  else if (iframe.webkitRequestFullScreen) {
    iframe.webkitRequestFullScreen();
  }

  function onYouTubePlayerReady(iframe) {
    ytplayer = document.getElementById(this.id);
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange");
  }

  function onytplayerStateChange(newState) {
    if ( newState == 0 ) {
     //cancel full-screen
     iframe.fullScreenCancel();
    }
  }

  }; // end onclick function  
} // end for statement 

在大多数情况下,事情正常运作。我有两个问题:

1)视频加载并能够进入全屏模式。但是,如果您单击YouTube视频播放器控件中的全屏按钮,它将保持全屏状态并在那里“卡住”。如果你没有点击它并点击“esc”键,它将全屏显示。 2)我在底部添加了一些代码来检测状态变化,然后自动将其从全屏中移出,但它似乎完全忽略了这一点。我不是javascript专家,也许有人知道解决这些问题的方法?我认为这些可能是与API相关的问题?欢迎任何想法!

1 个答案:

答案 0 :(得分:0)

您有一个函数onYouTubePlayerReady,在您发布的代码中的任何位置都没有调用。

我认为您可能遇到此问题: Why isn't the YouTube iframe player calling onYouTubePlayerReady when it's loaded?

当我尝试你的页面时,只需再次点击全屏图标,视频就会从全屏返回。视频仍会占据整个页面,因为您设置了iframe的大小,这真的是您想要的行为吗?