【问题标题】:How to load iframe on load using jquery?如何使用 jquery 在加载时加载 iframe?
【发布时间】:2013-09-07 09:59:30
【问题描述】:

以下是将 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);

            };
        }
    }

【问题讨论】:

    标签: javascript jquery html iframe youtube


    【解决方案1】:

    当你创建它时,只需创建一个 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.
           }
    }
    

    【讨论】:

    • 感谢您的回复。我有多个 div,所以我想加载多个视频,那么在这种情况下可以做什么?
    • @eegloo: 只需使用appendChild(iframe) 附加您想要的 div。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 1970-01-01
    • 2011-05-14
    • 1970-01-01
    • 2012-01-27
    • 2021-06-16
    相关资源
    最近更新 更多