lunes, 19 de octubre de 2015

Redimensionar iframe segun el tamaño de su contenido

Cuando desarrollamos una pagina web o sistema web muchas veces tenemos la necesidad de insertar iframes y nos topamos con el problema de que no podemos poner la altura al 100% de su contenido 

En este post mostrare la solucion a este problema
con este sencillo codigo javascript nativo y/o jquery redimensionaremos la altura del iframe.


Codigo javascript
  <html>
    <head>
       <script language="JavaScript">
         function rezise(obj){
          var height=obj.contentWindow.document.body.scrollHeight;
          obj.style.height=height;
         } 
       </script>
     </head>
     <body>
  <iframe id="miFrame" src="iframe.html" width="100%" height="0" frameborder="1" transparency="transparency" onload="rezise(this);"></iframe>
     </body>

  </html>
  

Codigo jquery
  <html>
    <head>
       <script language="JavaScript">
       function rezise(obj){
       jQuery.each(jQuery.browser, function(i, val) {
             if (val == true) {
                 brow = i.toString();
             }
         });
         var height=0;
         if (brow == 'mozilla') {
             height=$(obj).contents().find('body').outerHeight();
         }
         else if (brow == 'msie') {
             height=$(obj).contents().find('body').innerHeight();
         }
         else {
             height=$(obj).contents().find('body').height();
         }
         $(obj).css('height',height+ 'px');
  } 
 </script>
     </head>
     <body>
  <iframe id="miFrame" src="iframe.html" width="100%" height="0" frameborder="1" transparency="transparency" onload="rezise(this);"></iframe>
     </body>

  </html>
  
.

4 comentarios:

  1. Como puedes realizar esto, para que se ajuste a la pagina evitando el scroll

    ResponderEliminar
  2. Como puede hacerse sin modificar el codigo html del iframe? O al menos se puede fijar un mismo width y height a todos los iframes con javascript sin modificar html (solo javascript)

    ResponderEliminar
    Respuestas
    1. claro por ejemplo
      const iframes=document.querySelectorAll('iframe')
      iframes.forEach(function(iframe){
      iframe.style.width='50%';
      iframe.style.height='100px';
      })

      Eliminar