首页 文章

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

提问于
浏览
2

我有一个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元素的高度 . 我怎么 grab 它?

2 回答

  • 1

    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,而不包含任何其他内容 .

    亲切的问候 .

  • 2

    如果您对窗口的整个宽度不感兴趣,可以让它适合内容

    var frame = $('iframe#modal-body');
    
    frame.load(resizeIframe);
    function resizeIframe() {
        frame.height(frame.contents().height());
        frame.height(frame.contents().height());
    }
    

相关问题