javascript 在悬停/鼠标悬停时启动 youtube 视频
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20706799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Start youtube video on hover/mouseover
提问by seb
I'm trying to get youtube videos to start on hover. It will pause (not stop) when the user hovers over another video...
我正在尝试让 YouTube 视频在悬停时开始。当用户将鼠标悬停在另一个视频上时,它会暂停(而不是停止)...
I am stuck on the hover command. Can someone help me work it out please?
我被困在悬停命令上。有人可以帮我解决吗?
The page has 16 videos, this is the working code from the jsfiddle that contains 3 videos as an example.
该页面有 16 个视频,这是来自 jsfiddle 的工作代码,其中包含 3 个视频作为示例。
http://jsfiddle.net/sebwhite/gpJN4/
http://jsfiddle.net/sebwhite/gpJN4/
VIDEO:
视频:
<iframe id="player" width="385" height="230" src="http://www.youtube.com/embed/erDxb4IkgjM?rel=0&wmode=Opaque&enablejsapi=1;showinfo=0;controls=0" frameborder="0" allowfullscreen></iframe>
JAVASCRIPT:
爪哇脚本:
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onStateChange': onPlayerStateChange
}
});
onYouTubeIframeAPIReady();
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING) {
player1.pauseVideo();
player2.pauseVideo();
}
回答by Paul Rad
UPDATED FIDDLE
更新的小提琴
Try this:
试试这个:
var $$ = function(tagname) { return document.getElementsByTagName(tagname); }
function onYouTubeIframeAPIReady() {
var videos = $$('iframe'), // the iframes elements
players = [], // an array where we stock each videos youtube instances class
playingID = null; // stock the current playing video
for (var i = 0; i < videos.length; i++) // for each iframes
{
var currentIframeID = videos[i].id; // we get the iframe ID
players[currentIframeID] = new YT.Player(currentIframeID); // we stock in the array the instance
// note, the key of each array element will be the iframe ID
videos[i].onmouseover = function(e) { // assigning a callback for this event
var currentHoveredElement = e.target;
if (playingID) // if a video is currently played
{
players[playingID].pauseVideo();
}
players[currentHoveredElement.id].playVideo();
playingID = currentHoveredElement.id;
};
}
}
onYouTubeIframeAPIReady();
Fiddle:
小提琴: