【发布时间】:2015-04-14 19:54:08
【问题描述】:
我在这里有一个正在开发的 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相关的问题吗?欢迎任何想法!
【问题讨论】:
标签: javascript api youtube