function setIframeHeight(id){ try{ var iframe = document.getElementById(id); if(iframe.attachEvent){ iframe.attachEvent("onload", function(){ iframe.height = iframe.contentWindow.document.documentElement.scrollHeight; }); return; }else{ iframe.onload = function(){ iframe.height = iframe.contentDocument.body.scrollHeight; }; return; } }catch(e){ throw new Error('setIframeHeight Error'); } }
涉及了一些兼容问题:
IE用attachEvent | 3C用onload来判断子页面是否加载完成。
IE用contentWindow | 3C用contentDocument来获取子页面
IE用document.documentElement.scrollHeight(兼容ie6 ie7)| 3C用body.scrollHeight获取页面高度
子级页面给父级页面元素设置高度
function setParentIframeHeight(id){ try{ var parentIframe = parent.document.getElementById(id); if(window.attachEvent){ window.attachEvent("onload", function(){ parentIframe.height = document.documentElement.scrollHeight; }); return; }else{ window.onload = function(){ parentIframe.height = document.body.scrollHeight; }; return; } }catch(e){ throw new Error('setParentIframeHeight Error'); } }