Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

javascript - Start youtube video on hover/mouseover

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();
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
             if (playingID !== currentHoveredElement.id) {
               players[playingID].stopVideo();
             }
             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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...