2014-09-29 77 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