如何使用jquery在加载时加载iframe?

时间:2013-09-07 09:59:30

标签: javascript jquery html iframe youtube

以下是在html中嵌入youtube视频的功能。 在这个youtube视频显示点击,但我想在加载时使用javascript。 怎么办?有什么帮助吗?

youtubeLoadVideos : function () {        
        // Find all the YouTube video embedded on a page
        var videos = document.getElementsByClassName("youtube"); 
        for (var i=0; i<videos.length; i++) {         
            var youtube = videos[i];

            // Attach an onclick event to the YouTube Thumbnail
            youtube.onclick = function() {       
                // Create an iFrame with autoplay set to true
                var iframe = document.createElement("iframe");
                iframe.setAttribute("src", "https://www.youtube.com/embed/" + this.id); 

                // The height and width of the iFrame should be the same as parent
                iframe.style.width  = this.style.width;
                iframe.style.height = this.style.height;
                iframe.style.clear = 'both';

                // Replace the YouTube thumbnail with YouTube HTML5 Player
                this.parentNode.replaceChild(iframe, this);

            };
        }
    }

1 个答案:

答案 0 :(得分:1)

在创建onload时,只需创建一个html标记:

<iframe src="https://www.youtube.com/embed/yourid"/>

或者使用javascript,因为默认情况下只应加载1个:

window.onload = function(){
   var videos = document.getElementsByClassName("youtube"); 
   if (videos.length > 0){      
            var youtube = videos[0];
             var iframe = document.createElement("iframe");
            iframe.setAttribute("src", "https://www.youtube.com/embed/" + youtube.id); 

            // The height and width of the iFrame should be the same as parent
            iframe.style.width  = youtube.style.width;
            iframe.style.height = youtube.style.height;
            iframe.style.clear = 'both';

            // Replace the YouTube thumbnail with YouTube HTML5 Player
            youtube.parentNode.replaceChild(iframe, youtube);
   }
}

另一种情况,如果你需要保持onclick并默认加载1个视频,只需保留你的代码并写下更多行:

window.onload = function(){
       var videos = document.getElementsByClassName("youtube"); 
       if (videos.length > 0){      
            var youtube = videos[0]; //play the first video onload
            youtube.click(); //trigger click programmatically, this will cause the event handler to be executed and insert an iframe.
       }
}