javascript - 加载内部内容后调整大小 'iframe'

标签 javascript ajax iframe dom-events

我有一个 iFrame,在其中加载一个页面,该页面在单击各种页面标签后使用 ajax 加载数据。现在我使用 Javascript 函数来计算加载数据的高度以替换 iframe 的高度,这会导致调整 iframe 的大小,从而避免滚动条。现在我的问题是,一旦单击标签,脚本就会被调用,但数据仍在加载。请告诉我一些可以用来等待 ajax 完成加载数据然后调用我的函数的东西。

我正在使用以下脚本:

function resizeFrame() {
    var body = document.body,
    html = document.documentElement;
    var iFrame = parent.document.getElementById("iframe1");//get id of iframe from parent
    var nHeight=0;
    var iframeWin = iFrame.contentWindow.document.body ;
    nHeight = iframeWin.scrollHeight;
    iFrame.style.height = nHeight+'px'; //set the frame height to correspond to the content 
}

我的html如下:

<iframe src="" id="iframe1" name="iframe1" scrolling="no" frameborder="0" onload="$(document).ready(function(){resizeFrame();});"  style="width:960px;height:570px">

上面的代码对我来说效果很好(iframe/src url 都在同一个域中。)我还想获取 iframe 内容窗口页面中的 div 元素的高度。我如何捕获它?

最佳答案

html

<iframe id="containter-frame" 
        src="<url of the page>"
        frameborder="0"
        min-height="600px"
        width="100%">
</iframe>

javascript/jquery:

$(document).ready(function(){

    var frame = $('iframe#containter-frame');

    //hide document default scroll-bar
    document.body.style.overflow = 'hidden';


    frame.load(resizeIframe);   //wait for the frame to load
    $(window).resize(resizeIframe); 

    function resizeIframe() {
        var w, h;       

        //detect browser dimensions
            if($.browser.mozilla){
            h = $(window).height();
            w = $(window).width();                  
        }else{
            h = $(document).height();
            w = $(document).width();
        }

        //set new dimensions for the iframe
            frame.height(h);
        frame.width(w);
    }
});

这里的技巧是frame.load方法等待框架加载。之后,根据需要操纵高度和宽度。这里我设置的是覆盖整个屏幕。并且该页面仅包含一个 iframe,没有其他内容。

亲切的问候。

关于javascript - 加载内部内容后调整大小 'iframe',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10024547/

相关文章:

php ajax,如何在动态选择框上显示动态值

ajax - jQuery:在任何 Javascript 事件触发之前通过 *非 jQuery* AJAX 添加目标元素?超出了 live() 的范围?

html - 隐藏并再次显示 iframe 后音频标签不出现?

jquery - 从 iframe Jquery 中删除元素

javascript - 删除 iframe 中的一些文本

javascript - 如何从字符串中全局删除 "</br> "

javascript - 正确使用输入文本值属性功能的误区

javascript - 如何使用 CSS 伪元素修复 IE 对换行符的支持?

javascript - 使用 Ajax 获取随机维基百科摘录

javascript - 如何允许在 Google Chrome 应用程序中的 webview 内下载?