2012-10-11 94 views
3

我想找出一種方法來觸發一個YouTube視頻完成時的JavaScript模式彈出/彈出。如何在YouTube視頻結束時顯示彈出/彈出窗口?

我第一次在UpWorthy.com上看到了這一點。看到此視頻,用於例如當視頻結束:http://www.upworthy.com/bully-calls-news-anchor-fat-news-anchor-destroys-him-on-live-tv

我已通過將JS參數來嵌入代碼啓用的javascript API(enablejsapi = 1)

我使用這個簡單的模態腳本來實現模式:http://www.ericmmartin.com/projects/simplemodal/

如何獲取YouTube視頻的結尾以觸發它?

非常感謝

+0

你知道如果YouTube視頻結束是什麼事件觸發?這應該是api中的某個地方。 –

回答

0

使用onStateChange事件的YouTube播放器,並檢查當前播放狀態。如果狀態爲YT.PlayerState.ENDED那麼您可以觸發模式對話框。

從YouTube的JavaScript播放器API參考文件(有一些修改)

function onYouTubePlayerReady(playerId) { 
    ytplayer = document.getElementById(playerId); 
    ytplayer.addEventListener("onStateChange", "onytplayerStateChange"); 
} 

function onytplayerStateChange(newState) { 
    if(newState==YT.PlayerState.ENDED){ 
     //OPEN Modal dialog box here 
    } 
} 
+0

嗨Tariqulazam,我如何添加一個模式框給你上面給出的例子 –

2
<html> 
<head> 
<title>YT Test</title> 
<script type="text/javascript"> 
    <!-- 
     // 2. This code loads the IFrame Player API code asynchronously. 
     var tag = document.createElement('script'); 
     tag.src = "http://www.youtube.com/iframe_api"; 
     var firstScriptTag = document.getElementsByTagName('script')[0]; 
     firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

     // 3. This function creates an <iframe> (and YouTube player) after the API code downloads. 
     var player; 
     function onYouTubeIframeAPIReady() { 
     player = new YT.Player('player', { 
      height: '390', 
      width: '640', 
      videoId: 'ecccag3L-yw', 
      events: { 
      'onReady': onPlayerReady, 
      'onStateChange': onPlayerStateChange 
      } 
     }); 
     } 

     // The API will call this function when the video player is ready. 
     function onPlayerReady(event) { /* do nothing yet */ } 

     // The API calls this function when the player's state changes. 

     function onPlayerStateChange(event) { 
     if (event.data == YT.PlayerState.ENDED) { 
       // insert appropriate modal (or whatever) below 
       alert('I hope you enjoyed the video') 
     } 
     } 
     --> 

</script> 
</head> 
<body> 
<div id="player"></div> 
</body> 
<html>