redimensionar imagen dinamico dinamicamente crear contenido automatico alto ajustar ajustado html iframe height scrollbar

html - imagen - iframe sin scroll ajustado al contenido



¿Hacer iframe ajusta automáticamente la altura de acuerdo con el contenido sin usar la barra de desplazamiento? (17)

Esta pregunta ya tiene una respuesta aquí:

Por ejemplo:

<iframe name="Stack" src="http://stackoverflow.com/" width="740" frameborder="0" scrolling="no" id="iframe"> ... </iframe>

Quiero que pueda ajustar su altura de acuerdo con el contenido dentro de ella, sin usar scroll.


Agregue esto a su sección <head> :

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

Y cambia tu iframe a esto:

<iframe src="..." frameborder="0" scrolling="no" onload="resizeIframe(this)" />

Como se encuentra en la discusión de sitepoint .


Aquí hay una versión compacta:

<iframe src="hello.html" onload="this.style.height=this.contentDocument.body.scrollHeight +''px'';"> </iframe>


El método del método .contents () de jQuery nos permite buscar a través de los hijos inmediatos del elemento en el árbol DOM.

jQuery:

$(''iframe'').height( $(''iframe'').contents().outerHeight() );

Recuerda que el cuerpo de la página interior del iframe debe tener su altura.

CSS:

body { height: auto; overflow: auto }


Esta opción funcionará al 100%.

<iframe id=''iframe2'' src="url.com" frameborder="0" style="overflow: hidden; height: 100%; width: 100%; position: absolute;" height="100%" width="100%"></iframe>


Esto funciona para mí (en su mayoría).

Pon esto en la parte inferior de tu página.

<script type="application/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script type="application/javascript" src="/script/jquery.browser.js"> </script> <script type="application/javascript" src="/script/jquery-iframe-auto-height.js"> </script> <script type="application/javascript"> jQuery(''iframe'').iframeAutoHeight(); $(window).load( function() { jQuery(''iframe'').iframeAutoHeight(); } ); // for when content is not html e.g. a PDF function setIframeHeight() { $(''.iframe_fullHeight'').each( function (i, item) { item.height = $(document).height(); } ); }; $(document).ready( function () { setIframeHeight(); }); $(window).resize( function () { setIframeHeight(); }); </script>

La primera mitad es de ???, y funciona cuando hay html en el iframe. La segunda mitad establece el iframe a la altura de la página (no la altura del contenido), cuando la clase iframes es iframe_fullHeight . Puede usar esto si el contenido es un PDF u otro similar, pero tiene que configurar la clase. También se puede usar solo cuando la altura completa es apropiada.

Nota: por alguna razón, cuando se recalcula después de cambiar el tamaño de la ventana, la altura no es correcta.


Esto me funciona (también con varios iframes en una página):

$(''iframe'').load(function(){$(this).height($(this).contents().outerHeight());});


Evite JavaScript en línea; puedes usar una clase:

<iframe src="..." frameborder="0" scrolling="auto" class="iframe-full-height"></iframe>

Y referenciarlo con jQuery:

$(''.iframe-full-height'').on(''load'', function(){ this.style.height=this.contentDocument.body.scrollHeight +''px''; });


He tenido problemas en el pasado llamando a iframe.onload para iframes creados dinámicamente, así que seguí este enfoque para establecer el tamaño del iframe:

Vista iFrame

var height = $("body").outerHeight(); parent.SetIFrameHeight(height);

Vista principal

SetIFrameHeight = function(height) { $("#iFrameWrapper").height(height); }

(Esto solo funcionará si ambas vistas están en el mismo dominio)


La respuesta de hjpotter92 funciona bastante bien en ciertos casos, pero el contenido de iframe a menudo se recortó en Firefox e IE, aunque está bien en Chrome.

Lo siguiente funciona bien para mí y soluciona el problema de recorte. El código se encontró en http://www.dyn-web.com/tutorials/iframes/height/ . He hecho una ligera modificación para eliminar el atributo onload del HTML. Coloque el siguiente código después de la etiqueta <iframe> HTML y antes del cierre </body> :

<script type="text/javascript"> function getDocHeight(doc) { doc = doc || document; // .com/questions/1145850/ var body = doc.body, html = doc.documentElement; var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ); return height; } function setIframeHeight(id) { var ifrm = document.getElementById(id); var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document; ifrm.style.visibility = ''hidden''; ifrm.style.height = "10px"; // reset to minimal height ... // IE opt. for bing/msn needs a bit added or scrollbar appears ifrm.style.height = getDocHeight( doc ) + 4 + "px"; ifrm.style.visibility = ''visible''; } document.getElementById(''ifrm'').onload = function() { // Adjust the Id accordingly setIframeHeight(this.id); } </script>

Su iframe HTML:

<iframe id="ifrm" src="some-iframe-content.html"></iframe>

Tenga en cuenta que si prefiere incluir el Javascript en el <head> del documento, puede volver a utilizar un atributo de onload en línea en el iframe HTML, como en la página web de dyn-web .


La sugerencia de hjpotter92 no funciona en safari! He hecho un pequeño ajuste al script, por lo que ahora también funciona en Safari.

Solo el cambio realizado es restablecer la altura a 0 en cada carga para permitir que algunos navegadores disminuyan la altura.

Añade esto a la etiqueta <head> :

<script type="text/javascript"> function resizeIframe(obj){ obj.style.height = 0; obj.style.height = obj.contentWindow.document.body.scrollHeight + ''px''; } </script>

Y agrega el siguiente atributo onload a tu iframe, así

<iframe onload=''resizeIframe(this)''></iframe>


Lo hice con AngularJS. Angular no tiene una carga ng, pero se hizo un módulo de terceros; instálalo con la planta inferior a continuación, o encuéntrala aquí: https://github.com/andrefarzat/ng-load

Obtenga la directiva ngLoad: bower bower install ng-load --save

Configure su iframe:

<iframe id="CreditReportFrame" src="about:blank" frameborder="0" scrolling="no" ng-load="resizeIframe($event)" seamless></iframe>

Función resizeIframe del controlador:

$scope.resizeIframe = function (event) { console.log("iframe loaded!"); var iframe = event.target; iframe.style.height = iframe.contentWindow.document.body.scrollHeight + ''px''; };


Prueba esto para IE11

<iframe name="Stack" src="http://.com/" style=''height: 100%; width: 100%;'' frameborder="0" scrolling="no" id="iframe">...</iframe>


Puede usar esta biblioteca, que inicialmente ajusta el tamaño de su iframe correctamente y también la mantiene en el tamaño correcto detectando cada vez que cambia el tamaño del contenido del iframe (ya sea mediante la comprobación regular en un setInterval o mediante MutationObserver ) y redimensionándolo.

github.com/davidjbradshaw/iframe-resizer

Esto funciona con ambos iframes cruzados y del mismo dominio.


Quería hacer que un iframe comportara como una página normal (necesitaba hacer un banner de pantalla completa dentro de un elemento de iframe ), así que aquí está mi script:

(function (window, undefined) { var frame, lastKnownFrameHeight = 0, maxFrameLoadedTries = 5, maxResizeCheckTries = 20; //Resize iframe on window resize addEvent(window, ''resize'', resizeFrame); var iframeCheckInterval = window.setInterval(function () { maxFrameLoadedTries--; var frames = document.getElementsByTagName(''iframe''); if (maxFrameLoadedTries == 0 || frames.length) { clearInterval(iframeCheckInterval); frame = frames[0]; addEvent(frame, ''load'', resizeFrame); var resizeCheckInterval = setInterval(function () { resizeFrame(); maxResizeCheckTries--; if (maxResizeCheckTries == 0) { clearInterval(resizeCheckInterval); } }, 1000); resizeFrame(); } }, 500); function resizeFrame() { if (frame) { var frameHeight = frame.contentWindow.document.body.scrollHeight; if (frameHeight !== lastKnownFrameHeight) { lastKnownFrameHeight = frameHeight; var viewportWidth = document.documentElement.clientWidth; if (document.compatMode && document.compatMode === ''BackCompat'') { viewportWidth = document.body.clientWidth; } frame.setAttribute(''width'', viewportWidth); frame.setAttribute(''height'', lastKnownFrameHeight); frame.style.width = viewportWidth + ''px''; frame.style.height = frameHeight + ''px''; } } } //-------------------------------------------------------------- // Cross-browser helpers //-------------------------------------------------------------- function addEvent(elem, event, fn) { if (elem.addEventListener) { elem.addEventListener(event, fn, false); } else { elem.attachEvent("on" + event, function () { return (fn.call(elem, window.event)); }); } } })(window);

Las funciones son autoexplicativas y tienen comentarios para explicar con mayor detalle su propósito.


<script type="text/javascript"> function resizeIframe(obj) { obj.style.height = 0; obj.style.height = obj.contentWindow.document.body.scrollHeight + ''px''; } </script>

Esto no funciona para Chrome. Pero trabajando para firefox.


function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newheight=document.getElementById(id).contentWindow.document.body.scrollHeight; newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth; } document.getElementById(id).height=(newheight) + "px"; document.getElementById(id).width=(newwidth) + "px"; }

agregue esto a su iframe: onload = "autoResize (''youriframeid'')"


jq2(''#stocks_iframe'').load(function(){ var iframe_width = jq2(''#stocks_iframe'').contents().outerHeight() ; jq2(''#stocks_iframe'').css(''height'',iframe_width); }); <iframe id=''stocks_iframe'' style=''width:100%;height:0px;'' frameborder=''0''>