Start youtube video on hover/mouseover

守給你的承諾、 提交于 2019-12-29 05:00:32

问题


I'm trying to get youtube videos to start on hover. It will pause (not stop) when the user hovers over another video...

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.

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();
 }

回答1:


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:

http://jsfiddle.net/gpJN4/3/



来源:https://stackoverflow.com/questions/20706799/start-youtube-video-on-hover-mouseover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!