我有一个 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/