2017-02-27 197 views
0

我目前正在使用各種iframe youtube嵌入滑塊的頁面。youtube iframe api不暫停視頻

我想讓我的JS暫停視頻,當你點擊滑塊上的「下一步」按鈕。我想我已經根據api設置了一切...但是,當您單擊滑塊按鈕時,它似乎沒有暫停視頻。

<script type="text/javascript"> 
// https://developers.google.com/youtube/iframe_api_reference 

// global variable for the player 
var player; 

// this function gets called when API is ready to use 

function onYouTubePlayerAPIReady() { 
    // create the global player from the specific iframe (#video) 
    player = new YT.Player('video', { 
    events: { 
     // call this function when player is ready to use 
     'onReady': onPlayerReady 
    } 
    }); 
} 

function onPlayerReady(event) { 

    // bind events 

    var pauseButtonRight = document.getElementByID("pause-right"); 
    pauseButtonRight.addEventListener("click", function() { 
    player.pauseVideo(); 
    }); 
    var pauseButtonLeft = document.getElementByID("pause-left"); 
    pauseButtonLeft.addEventListener("click", function() { 
    player.pauseVideo(); 
    }); 
} 

// Inject YouTube API script 
var tag = document.createElement('script'); 
tag.src = "//www.youtube.com/player_api"; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 
</script> 

我的I幀:

<iframe src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe> 

任何方向將不勝感激。

回答

0

有幾件事情:

  • 這是document.getElementByIddocument.getElementByID你實例化一個YouTube播放器ID 'video'但你的iframe中沒有任何標識
  • <iframe id="video" src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe> 
    
  • 使用onYouTubeIframeAPIReady而不是onYouTubePlayerAPIReady

你會碰到這樣的:

var player; 

function onYouTubeIframeAPIReady() { 

    // create the global player from the specific iframe (#video) 
    player = new YT.Player('video', { 
    events: { 
     // call this function when player is ready to use 
     'onReady': onPlayerReady 
    } 
    }); 
} 

function onPlayerReady(event) { 
    var pauseButtonRight = document.getElementById("pause"); 
    pauseButtonRight.addEventListener("click", function() { 
    player.pauseVideo(); 
    }); 
    var pauseButtonLeft = document.getElementById("play"); 
    pauseButtonLeft.addEventListener("click", function() { 
    player.playVideo(); 
    }); 
} 

// Inject YouTube API script 
var tag = document.createElement('script'); 
tag.src = "//www.youtube.com/player_api"; 
var firstScriptTag = document.getElementsByTagName('script')[0]; 
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); 

有:

<iframe id="video" src="https://www.youtube.com/embed/6QB6jVjA2js?enablejsapi=1&html5=1&" frameborder="0" allowfullscreen="0"></iframe> 
<input id="pause" type="submit" value="pause" /> 
<input id="play" type="submit" value="play" /> 

檢查this fiddle

檢查Youtube iframe API reference

+0

謝謝您的幫助,這個...這個工作大。 – chadisfred