如果“src”发生变化,我怎样才能让iframe自动调整大小? (使用jQuery)

时间:2011-02-01 20:26:34

标签: javascript jquery iframe

我写了这段代码:

$('#main-content > iframe').load(function(){
    var $document = $(this.contentWindow.document);
    alert($document.height());
    $(this).height($document.height());
});

这在页面首次加载时有效,但是当用户在使用页面时更改iframe的src时,它不会调整大小。

我改变了这样的src:

$('#main-content > iframe').attr("src",href);

无需担心XSS - 它都是本地的。

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

<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>

答案 1 :(得分:-1)

在Internet Explorer中,您可以向iframe的onreadystatechange添加一个eventlistener,根据我的经验,它比load

更可靠地工作

可在msdn

找到更多信息

示例:

$('#main-content > iframe')[0].onreadystatechange = function(evt)
{
    if(window.event)
        evt = window.event;
    var $document = $(evt.srcElement);
    alert($document.height());
    $(this).height($document.height());
}

请注意,我还没有测试过代码