etiqueta ejemplos ejemplo contenido codigo automatico ajustar javascript html iframe adjustment

javascript - ejemplos - iframe height automatico



Ajusta el ancho y alto del iframe para que se ajuste al contenido. (27)

Contexto

Tuve que hacer esto yo mismo en el contexto de una extensión web. Esta extensión web inyecta un poco de IU en cada página, y esta IU vive dentro de un iframe . El contenido dentro del iframe es dinámico, por lo que tuve que reajustar el ancho y la altura del propio iframe .

Utilizo React pero el concepto se aplica a cada biblioteca.

Mi solución (esto supone que usted controla tanto la página como el iframe)

Dentro del iframe cambié body estilos de body para tener dimensiones realmente grandes. Esto permitirá que los elementos del interior se distribuyan utilizando todo el espacio necesario. Hacer width y height 100% no me funcionó (supongo que porque el iframe tiene un width = 300px predeterminado width = 300px y height = 150px )

/* something like this */ body { width: 99999px; height: 99999px; }

Luego inyecté toda la interfaz de usuario de iframe dentro de un div y le di algunos estilos

#ui-root { display: ''inline-block''; }

Después de representar mi aplicación dentro de este #ui-root (en Reaccionar , hacer esto dentro de componentDidMount ) calculo las dimensiones de este div como y las sincronizo con la página principal usando window.postMessage :

let elRect = el.getBoundingClientRect() window.parent.postMessage({ type: ''resize-iframe'', payload: { width: elRect.width, height: elRect.height } }, ''*'')

En el marco padre hago algo como esto:

window.addEventListener(''message'', (ev) => { if(ev.data.type && ev.data.type === ''resize-iframe'') { iframe.style.width = ev.data.payload.width + ''px'' iframe.style.height = ev.data.payload.height + ''px'' } }, false)

Necesito una solución para ajustar automáticamente el width y la height de un iframe para que se ajuste a su contenido. El punto es que el ancho y la altura se pueden cambiar después de que se haya cargado el iframe . Supongo que necesito una acción de evento para lidiar con el cambio en las dimensiones del cuerpo contenido en el iframe.


Aquí hay una solución de navegador cruzado si no quieres usar jQuery:

/** * Resizes the given iFrame width so it fits its content * @param e The iframe to resize */ function resizeIframeWidth(e){ // Set width of iframe according to its content if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax e.width = e.contentWindow.document.body.scrollWidth; else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax e.width = e.contentDocument.body.scrollWidth + 35; else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8 e.width = e.contentDocument.body.offsetWidth + 35; }


Aquí hay varios métodos:

<body style="margin:0px;padding:0px;overflow:hidden"> <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe> </body>

Y OTRA ALTERNATIVA

<body style="margin:0px;padding:0px;overflow:hidden"> <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe> </body>

PARA OCULTAR EL DESPLAZAMIENTO CON 2 ALTERNATIVAS COMO SE MUESTRA ANTERIORMENTE

<body style="margin:0px;padding:0px;overflow:hidden"> <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:150%;width:150%" height="150%" width="150%"></iframe> </body>

HACK CON SEGUNDO CÓDIGO

<body style="margin:0px;padding:0px;overflow:hidden"> <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:150%;width:150%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="150%" width="150%"></iframe> </body>

Para ocultar las barras de desplazamiento del iFrame, el padre se "desborda: oculto" para ocultar las barras de desplazamiento y el iFrame está diseñado para alcanzar una anchura y altura de hasta el 150%, lo que fuerza a las barras de desplazamiento fuera de la página y, como el cuerpo no lo hace t tiene barras de desplazamiento, uno no puede esperar que el iframe exceda los límites de la página. ¡Esto oculta las barras de desplazamiento del iFrame con ancho completo!

fuente: establecer iframe auto height


Así es como lo haría (probado en FF / Chrome):

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript"> function autoResize(iframe) { $(iframe).height($(iframe).contents().find(''html'').height()); } </script> <iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>


Así es como lo hice onload o cuando las cosas cambian.

parent.jQuery("#frame").height(document.body.scrollHeight+50);


Después de haber intentado todo en la tierra, esto realmente funciona para mí.

index.html

<style type="text/css"> html, body{ width:100%; height:100%; overflow:hidden; margin:0px; } </style> <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type="text/javascript"> function autoResize(iframe) { $(iframe).height($(iframe).contents().find(''html'').height()); } </script> <iframe src="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>



En jQuery, esta es la mejor opción para mí, ¡realmente me ayuda! Espero que te ayude!

iframe

<iframe src="" frameborder="0" id="iframe" width="100%"></iframe>

jQuery

<script> var valueSize = $( "#iframe" ).offset(); var totalsize = (valueSize.top * 2) + valueSize.left; $( "#iframe" ).height(totalsize); </script>


Encontré este cambio de tamaño para trabajar mejor:

function resizer(id) { var doc = document.getElementById(id).contentWindow.document; var body_ = doc.body; var html_ = doc.documentElement; var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight ); var width = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth ); document.getElementById(id).height = height; document.getElementById(id).width = width; }

Tenga en cuenta que el objeto de estilo es eliminado.



Esta es una solución de prueba sólida

function resizer(id) { var doc=document.getElementById(id).contentWindow.document; var body_ = doc.body, html_ = doc.documentElement; var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight ); var width = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth ); document.getElementById(id).style.height=height; document.getElementById(id).style.width=width; }

el html

<IFRAME SRC="blah.php" id="iframe1" onLoad="resizer(''iframe1'');"></iframe>


Esto usa solo CSS en línea:

<iframe src="http://example.com" style="resize: both;" onload="this.style.height=this.contentDocument.body.scrollHeight +''px''; this.style.width=this.contentDocument.body.scrollWidth +''px'';" onresize="this.style.height=this.contentDocument.body.scrollHeight +''px''; this.style.width=this.contentDocument.body.scrollWidth +''px'';"> </iframe>


Estoy usando este código para ajustar automáticamente la altura de todos los iframes (con clase autoHeight) cuando se cargan en la página. Probado y funciona en IE, FF, Chrome, Safari y Opera.

function doIframe() { var $iframes = $("iframe.autoHeight"); $iframes.each(function() { var iframe = this; $(iframe).load(function() { setHeight(iframe); }); }); } function setHeight(e) { e.height = e.contentWindow.document.body.scrollHeight + 35; } $(window).load(function() { doIframe(); });


He modificado ligeramente la gran solución de Garnaph arriba. Parecía que su solución modificó el tamaño del iframe según el tamaño justo antes del evento. Para mi situación (envío de correo electrónico a través de un iframe) necesitaba la altura del iframe para cambiar justo después del envío. Por ejemplo, muestre los errores de validación o el mensaje de "agradecimiento" después del envío.

Acabo de eliminar la función click () anidada y la puse en mi html de iframe:

<script type="text/javascript"> jQuery(document).ready(function () { var frame = $(''#IDofiframeInMainWindow'', window.parent.document); var height = jQuery("#IDofContainerInsideiFrame").height(); frame.height(height + 15); }); </script>

Funcionó para mí, pero no estoy seguro acerca de la funcionalidad de navegador cruzado.


Me di cuenta de otra solución después de algunos experimentos. Originalmente probé el código marcado como "mejor respuesta" a esta pregunta y no funcionó. Mi conjetura es porque mi iframe en mi programa en ese momento fue generado dinámicamente. Aquí está el código que usé (funcionó para mí):

Javascript dentro del iframe que se está cargando:

window.onload = function() { parent.document.getElementById(''fileUploadIframe'').style.height = document.body.clientHeight+5+''px''; parent.document.getElementById(''fileUploadIframe'').style.width = document.body.clientWidth+18+''px''; };

Es necesario agregar 4 o más píxeles a la altura para eliminar las barras de desplazamiento (algunos errores / efectos extraños de iframes). El ancho es aún más extraño, es seguro agregar 18px al ancho del cuerpo. También asegúrese de tener el css para el cuerpo del iframe aplicado (abajo).

html, body { margin:0; padding:0; display:table; } iframe { border:0; padding:0; margin:0; }

Aquí está el html para el iframe:

<iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>

Aquí está todo el código dentro de mi iframe:

<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>File Upload</title> <style type="text/css"> html, body { margin:0; padding:0; display:table; } </style> <script type="text/javascript"> window.onload = function() { parent.document.getElementById(''fileUploadIframe'').style.height = document.body.clientHeight+5+''px''; parent.document.getElementById(''fileUploadIframe'').style.width = document.body.clientWidth+18+''px''; }; </script> </head> <body> This is a test.<br> testing </body> </html>

He realizado pruebas en chrome y un poco en firefox (en windows xp). Todavía tengo más pruebas que hacer, así que, por favor, dime cómo funciona esto para ti.


Para atributo de directiva angularjs:

G.directive ( ''previewIframe'', function () { return { restrict : ''A'', replace : true, scope : true, link : function ( scope, elem, attrs ) { elem.on ( ''load'', function ( e ) { var currentH = this.contentWindow.document.body.scrollHeight; this.style.height = eval( currentH ) + ( (25 / 100)* eval( currentH ) ) + ''px''; } ); } }; } );

Observe el porcentaje, lo inserté para que pueda contrarrestar el escalamiento que generalmente se realiza para iframe, texto, anuncios, etc., simplemente ponga 0 si no se implementa ningún escalado.


Plugin de jQuery para todos los navegadores.

Cross-bowser, library dominios cruzados que utiliza mutationObserver para mantener el tamaño de iFrame en el contenido y postMessage para comunicarse entre iFrame y la página de host. Funciona con o sin jQuery.


Sé que la publicación es antigua, pero creo que esta es otra manera de hacerlo. Acabo de implementar en mi código. Funciona perfectamente tanto en la carga de página como en el tamaño de página:

var videoHeight; var videoWidth; var iframeHeight; var iframeWidth; function resizeIframe(){ videoHeight = $(''.video-container'').height();//iframe parent div''s height videoWidth = $(''.video-container'').width();//iframe parent div''s width iframeHeight = $(''.youtubeFrames'').height(videoHeight);//iframe''s height iframeWidth = $(''.youtubeFrames'').width(videoWidth);//iframe''s width } resizeIframe(); $(window).on(''resize'', function(){ resizeIframe(); });


Si el contenido del iframe es del mismo dominio, esto debería funcionar muy bien. Sin embargo, sí requiere jQuery.

$(''#iframe_id'').load(function () { $(this).height($(this).contents().height()); $(this).width($(this).contents().width()); });

Para que se redimensione dinámicamente puedes hacer esto:

<script language="javaScript"> <!-- function autoResize(){ $(''#themeframe'').height($(''#themeframe'').contents().height()); } //--> </script> <iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>

Luego en la página que carga el iframe agrega esto:

<script language="javaScript"> function resize() { window.parent.autoResize(); } $(window).on(''resize'', resize); </script>


Si el contenido es solo un html muy simple, la forma más sencilla es eliminar el iframe con javascript

html:

<div class="iframe"> <iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe> </div>

javascript:

function removeIframe(obj)( var iframeDocument = obj.contentDocument || obj.contentWindow.document; var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML; obj.remove(); document.getElementsByClassName("iframe")[0].innerHTML = mycontent; }


Si puede controlar tanto el contenido de IFRAME como la ventana principal, necesita el iFrame Resizer .

Esta biblioteca permite el cambio de tamaño automático de la altura y el ancho de los mismos iFrames de ambos dominios para adaptarse a su contenido contenido. Proporciona una gama de características para abordar los problemas más comunes con el uso de iFrames, que incluyen:

  • Altura y ancho de redimensionamiento del iFrame al tamaño del contenido.
  • Funciona con múltiples iFrames anidados.
  • Autenticación de dominio para iFrames de dominios cruzados.
  • Proporciona una gama de métodos de cálculo de tamaño de página para admitir diseños CSS complejos.
  • Detecta cambios en el DOM que pueden hacer que la página cambie de tamaño usando MutationObserver.
  • Detecta eventos que pueden hacer que la página cambie de tamaño (tamaño de ventana, animación y transición CSS, cambio de orientación y eventos de mouse).
  • Mensajería simplificada entre iFrame y la página de host a través de postMessage.
  • Corrige los enlaces de página en iFrame y admite enlaces entre el iFrame y la página principal.
  • Proporciona métodos personalizados de tamaño y desplazamiento.
  • Expone la posición principal y el tamaño de la ventana gráfica al iFrame.
  • Trabaja con ViewerJS para admitir documentos PDF y ODF.
  • Soporte de retroceso hasta IE8.

Simplicidad

var iframe = $("#myframe"); $(iframe.get(0).contentWindow).on("resize", function(){ iframe.width(iframe.get(0).contentWindow.document.body.scrollWidth); iframe.height(iframe.get(0).contentWindow.document.body.scrollHeight); });


Solución de una sola línea para incrustaciones: comienza con un tamaño mínimo y aumenta el tamaño del contenido. No hay necesidad de etiquetas de script.

<iframe src="http://URL_HERE.html" onload=''javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));'' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>


Todas las soluciones dadas hasta ahora solo cuentan para un cambio de tamaño único. Menciona que desea poder cambiar el tamaño del iFrame después de que se modifiquen los contenidos. Para hacer esto, necesita ejecutar una función dentro del iFrame (una vez que se cambian los contenidos, debe activar un evento para decir que los contenidos han cambiado).

Me quedé atrapado con esto por un tiempo, ya que el código dentro del iFrame parecía limitado al DOM dentro del iFrame (y no podía editar el iFrame), y el código ejecutado fuera del iFrame estaba pegado con el DOM fuera del iFrame (y no podía t recoger un evento que viene desde dentro del iFrame).

La solución provino de descubrir (a través de la asistencia de un colega) que a jQuery se le puede decir qué DOM debe usar. En este caso, el DOM de la ventana padre.

Como tal, un código como este hace lo que necesita (cuando se ejecuta dentro del iFrame):

<script type="text/javascript"> jQuery(document).ready(function () { jQuery("#IDofControlFiringResizeEvent").click(function () { var frame = $(''#IDofiframeInMainWindow'', window.parent.document); var height = jQuery("#IDofContainerInsideiFrame").height(); frame.height(height + 15); }); }); </script>


Todos no pueden trabajar utilizando los métodos anteriores.

javascript:

function resizer(id) { var doc = document.getElementById(id).contentWindow.document; var body_ = doc.body, html_ = doc.documentElement; var height = Math.max(body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight); var width = Math.max(body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth); document.getElementById(id).style.height = height; document.getElementById(id).style.width = width; }

html:

<div style="background-color:#b6ff00;min-height:768px;line-height:inherit;height:inherit;margin:0px;padding:0px;overflow:visible" id="mainDiv" > <input id="txtHeight"/>height <input id="txtWidth"/>width <iframe src="head.html" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" style="width:100%; height: 47px" frameborder="0" ></iframe> <iframe src="left.aspx" name="leftFrame" scrolling="yes" id="Iframe1" title="leftFrame" onload="resizer(''Iframe1'');" style="top:0px;left:0px;right:0px;bottom:0px;width: 30%; border:none;border-spacing:0px; justify-content:space-around;" ></iframe> <iframe src="index.aspx" name="mainFrame" id="Iframe2" title="mainFrame" scrolling="yes" marginheight="0" frameborder="0" style="width: 65%; height:100%; overflow:visible;overflow-x:visible;overflow-y:visible; " onload="resizer(''Iframe2'');" ></iframe> </div>

Env: IE 10, Windows 7 x64


Javascript para ser colocado en el encabezado:

function resizeIframe(obj) { obj.style.height = obj.contentWindow.document.body.scrollHeight + ''px''; }

Aquí va el código html iframe:

<iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>

Hoja de estilo css

>

.spec_iframe { width: 100%; overflow: hidden; }


<script type="application/javascript"> function resizeIFrameToFitContent( iFrame ) { iFrame.width = iFrame.contentWindow.document.body.scrollWidth; iFrame.height = iFrame.contentWindow.document.body.scrollHeight; } window.addEventListener(''DOMContentLoaded'', function(e) { var iFrame = document.getElementById( ''iFrame1'' ); resizeIFrameToFitContent( iFrame ); // or, to resize all iframes: var iframes = document.querySelectorAll("iframe"); for( var i = 0; i < iframes.length; i++) { resizeIFrameToFitContent( iframes[i] ); } } ); </script> <iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>