Ho bisogno di una soluzione per auto-regolare la larghezza
e altezza
di un iframe
per adattarsi appena al suo contenuto. Il punto è che la larghezza e l'altezza possono essere cambiate dopo che il iframe
è stato caricato. Credo di aver bisogno di un'azione evento per gestire il cambiamento delle dimensioni del corpo contenuto nell'iframe.
<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>
Cross-browser plug-in jQuery.
Cross-bowser, cross domain libreria che usa mutationObserver
per mantenere l'iFrame dimensionato al contenuto e postMessage
per comunicare tra iFrame e la pagina host. Funziona con o senza jQuery.
Ecco una soluzione cross-browser se non volete usare 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;
}