How can I get an iframe to automatically resize whenever its "src" changes? (using jQuery)
I've written this code:
$('#main-content > iframe').load(function(){
var $document = $(this.contentWindow.document);
alert($document.height());
$(this).height($document.height());
});
This works when the page first loads, but when the user changes the src
of the iframe while using the page, it doesn't resize.
I change the开发者_如何转开发 src like this:
$('#main-content > iframe').attr("src",href);
No need to worry about XSS - it's all local.
Any suggestions?
<script type="text/javascript">
$(document).ready(function(){
$('#main-content > iframe').attr('src','onmouseclick.html');
set();
});
function set() {
$('#main-content > iframe').load(function(){
var $document = $(this.contentWindow.document);
//alert($document.height());
$(this).height($document.height());
});
}
</script>
<div id="main-content">
<iframe id="main-contentiframe"></iframe>
<a href="onmouseclick.html" onmouseover="$('#main-content > iframe').attr('src',this.href);set();return false;">Link</a>
<a href="testscript.html" onmouseover="$('#main-content > iframe').attr('src',this.href);set();return false;">Link</a>
</div>
In Internet Explorer you can add an eventlistener to the onreadystatechange
of iframes, in my experience it works more reliably than load
More information can be found at msdn
Example:
$('#main-content > iframe')[0].onreadystatechange = function(evt)
{
if(window.event)
evt = window.event;
var $document = $(evt.srcElement);
alert($document.height());
$(this).height($document.height());
}
Beware, I have not tested the code
精彩评论