YouTube IFrame API on Internet Explorer and Firefox

拈花ヽ惹草 提交于 2019-12-03 08:27:56

问题


More of an "answer" than a "question", but not having found this elsewhere I'm posting it here.

I was having difficulty initializing the iFrame API in all versions of IE and Firefox, with a somewhat custom implementation. Basically, it would load the API, but wouldn't create the player object.

After a bit of trial and error, I finally figured out it wasn't working because the div ID I was passing to the object had its CSS visibility set to 'none'. Once it was set to 'visible' the whole thing worked. After that I tried setting the div CSS to 'display:none' (the app required the video to be hidden until requested by the user) which also caused the iFrame API to fail silently (never calling back 'onPlayerReady').

So, long story short, when using the YouTube iFrame API to initialize on a div that you want to remain hidden until later, use a CSS technique like absolute positioning to push it off screen until you want it later. Also, found that once the player object is initialized and 'onPlayerReady' has been called you could turn display on and off all day long and everything would still work as expected.


回答1:


You should leave the player conainer empty e.g.

<div class="myPlayerContainer"></div>

and when you want to show it just append it to container:

$('#showVideoBtn').click(function(){
    $('.myPlayerContainer').show().append('~ code of youtube iframe ~');
});



回答2:


Yotam is right, look at the following:

HTML:

<button onclick="toggleYoutube();">show / hide</button>
<div id="youtube"></div>

JS ( using jQuery ):

var visible = false;
function toggleYoutube() {
    visible = !visible;
    if ( visible ) {
        $("#youtube").append( '<iframe id="video" width="640" height="360" src="http://www.youtube-nocookie.com/embed/cjvIeNt93nc?rel=0" frameborder="0" allowfullscreen></iframe>' );
    } else {
        $("#video").remove();
    }
}

See full code at http://jsfiddle.net/wFVhT/2/



来源:https://stackoverflow.com/questions/14147677/youtube-iframe-api-on-internet-explorer-and-firefox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!