IE8下处理iframe自适应高度的小问题
时间:2010-12-24 来源:yicone
function autoSetFrameHeight(name) {
try {
var iframe;
if (!name) return;
iframe = document.getElementById(name);
if (iframe.contentDocument)
$("#" + name).height(iframe.contentDocument.height + "px");
else
$("#" + name).height(document.frames[name].document.body.scrollHeight + "px");
}
catch (e) {
// alert(e.message);
}
}
今天有用户反应IE8下某个弹窗(iframe内嵌个小页面)显示不完全, 后经测试, iframe.contentDocument.height在IE8下无效, 在IE6-7, Chrome, Firefox3~4下
改为iframe.contentDocument.body.offsetHeight后, 在IE6-8, Chrome, Firefox3~4下测试通过.
本文的示例代码运行在真实项目中, 但由于iframe目标页面承载的内容较为简单, 因此并未测试iframe目标页面中包含绝对定位层展开/折叠, 以及包含float层的情况,
也未处理某些文章提及的"非IE浏览器会有长高了缩不回去"的情形. 请读者注意.
參考資料: (請讀者自行驗證原文內容, 辯證接受)
- http://www.cnblogs.com/yuhe7919/archive/2009/11/04/iframe.html
-
http://blog.pchome.net/article/194139.html
此文中提及的代碼示例, 建議不要再採用了, 如果第一句取高度的代碼由於瀏覽器兼容性問題產生異常, 則此段代碼完全失效. 另外, 採用兩個高度比較的作法也沒有意義, 有些繞道並且繞遠了的感覺.
try {
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;} catch(ex) { }