2014-09-29 130 views
0

我创建了一个函数,当用户将鼠标悬停在某个div上时,插入一个YouTube iframe的功能when the user leaves div the video is paused. Everythings正常工作,但用户离开div时视频不会暂停。将鼠标暂停YouTube视频

小提琴:http://jsfiddle.net/508oknm7/20/

任何想法?谢谢!

var tag = document.createElement('script'), 
    firstScriptTag = document.getElementsByTagName('script')[0]; 

tag.src = "https://www.youtube.com/player_api"; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 
var player; 
$(".video_wrap").on({ 
    mouseenter: function() { 

     player = new YT.Player($(this).attr('id'), { 
      height: '240', 
      width: '320', 
      videoId: 'wJnnT1SGEsc', 
      playerVars: { 
      wmode: "transparent", 
      controls: 0, 
      showinfo: 0, 
      rel: 0, 
      modestbranding: 1, 
      iv_load_policy: 3 //anottations 
      }, 
      events: { 
       'onReady': onPlayerReady, 
       'onStateChange': onPlayerStateChange 
      } 
     }); 

     function onPlayerReady(event) { 
      event.target.playVideo(); 
     } 


    }, 
    mouseleave: function() { 
     player.pauseVideo(); 
    } 
}); 

回答

1

的API可能没有准备好 - 按the youtube Iframe API,你需要实现onYoutubeIframeAPIReady功能。

试试这个:

var tag = document.createElement('script'), 
    firstScriptTag = document.getElementsByTagName('script')[0]; 

tag.src = "https://www.youtube.com/player_api"; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 
var player; 
function onYouTubeIframeAPIReady(){ 
$(".video_wrap").on({ 
    mouseenter: function() { 

     player = new YT.Player($(this).attr('id'), { 
      height: '240', 
      width: '320', 
      videoId: 'wJnnT1SGEsc', 
      playerVars: { 
      wmode: "transparent", 
      controls: 0, 
      showinfo: 0, 
      rel: 0, 
      modestbranding: 1, 
      iv_load_policy: 3 //anottations 
      }, 
      events: { 
       'onReady': onPlayerReady, 
       'onStateChange': onPlayerStateChange 
      } 
     }); 

     function onPlayerReady(event) { 
      event.target.playVideo(); 
     } 


    }, 
    mouseleave: function() { 
     player.pauseVideo(); 
    } 
}); 
} 

请注意,这只是一个猜测,但如果你想更具体的东西,你可以提供的jsfiddle。编辑:This works for the first time

之后不起作用的原因是因为不再有mouseleave--因为不再有mouseenter - iframe完全覆盖了以前的div,因此你永远不会输入它,所以你不能离开它。

您想为此使用mouseout。

+1

小提琴:http://jsfiddle.net/508oknm7/20/ @Etai – 2014-09-29 19:18:39

+0

@rexhin我更新了我的答案。干杯。 – Etai 2014-09-29 20:20:01

+1

谢谢,多个divs呢?我需要它与多个@Etai合作 – 2014-09-29 20:39:36