0

以下是将 youtube 视频嵌入 html 的功能。在此 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);

            };
        }
    }
4

1 回答 1

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.
       }
}
于 2013-09-07T10:03:53.470 回答