2014-09-28 63 views
0

我想在用戶將鼠標懸停在div上時插入一個iframe,但它似乎沒有工作。沒有懸停事件,它工作得很好,但不是on hover函數。將鼠標懸停插入YouTube iframe

HTML:

<div class="video_wrap"></div> 

CSS:

.video_wrap { 
    width: 320px; 
    height: 240px; 
    background: #b30054; 
} 

JS:

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

tag.src = "https://www.youtube.com/player_api"; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

$(".video_wrap").on({ 
    mouseenter: function() { 

     $(this).attr('id', 'curr'); 

     var player; 

     function onYouTubePlayerAPIReady() { 
      player = new YT.Player('curr', { 
       height: '240', 
       width: '320', 
       videoId: 'wJnnT1SGEsc', 
      }); 
     }; 

    }, 
    mouseleave: function() { 
     //stuff to do on mouse leave 
    } 
}); 

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

回答

2

你不聲明事件處理程序中的onyoutubeready函數。一旦腳本加載完畢,該事件就會發出,這是毫無意義的。相反,您只需在懸停中構建播放器。

$(".video_wrap").on({ 
    mouseenter: function() { 

     $(this).prop('id', 'curr'); 

     player = new YT.Player('curr', { 
      height: '240', 
      width: '320', 
      videoId: 'wJnnT1SGEsc', 
     }); 


    }, 
    mouseleave: function() { 
     //stuff to do on mouse leave 
    } 
}); 

jsFiddle

+1

感謝它的工作原理;) – 2014-09-28 18:51:59