2013-09-07 3 views
0

Voici la fonction pour intégrer la vidéo youtube en html. Dans cet affichage vidéo youtube sur le clic, mais je veux le faire sur le chargement en utilisant javascript. Comment peut-on faire? De l'aide?Comment charger iframe en charge avec jquery?

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); 

      }; 
     } 
    } 

Répondre

1

Comme vous le créez onload, il suffit de créer une balise html:

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

Ou utiliser javascript, car il n'y a que 1 devrait être chargé par défaut:

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); 
    } 
} 

Un autre cas , si vous avez besoin de garder l'onclick et de charger 1 vidéo par défaut, gardez simplement votre code et écrivez quelques lignes supplémentaires:

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. 
     } 
} 
+0

Merci pour votre réponse. J'ai plus d'un div donc je veux charger plus d'une vidéos Alors, que peut-on faire dans ce cas? – eegloo

+1

@eegloo: utilisez simplement appendChild (iframe) pour ajouter le div désiré. –

+0

Merci beaucoup. Maintenant ça fonctionne bien. – eegloo