Iframe自适应高度,Iframe高度问题解决
================================
©Copyright 蕃薯耀 2021-03-10
https://www.cnblogs.com/fanshuyao/
一、Iframe自适应高度方法
/**
* 父级页面获取子级页面的高度 给元素设置高度
* 在onload事件之后才生效,即第一次加载才生效,后面高度变化不再生效
* @param id
* @returns
*/
function setIframeHeightAfterLoad(id){
try{
var iframe = document.getElementById(id);
if(iframe.attachEvent){
iframe.attachEvent("onload", function(){
//console.log("iframe.attachEvent");
iframe.height = iframe.contentWindow.document.documentElement.scrollHeight;
});
return;
}else{
iframe.onload = function(){
iframe.height = iframe.contentDocument.body.scrollHeight;
//console.log("iframe.onload");
};
return;
}
}catch(e){
throw new Error('setIframeHeightAfterLoad Error');
}
};
/**
* 父级页面获取子级页面的高度 给元素设置高度
* 配合定时使用:window.setInterval("thisIframeHeightAuto()", 200);
* @param id
* @returns
*/
function setIframeHeight(id){
try{
var iframe = document.getElementById(id);
if(iframe.attachEvent){
iframe.height = iframe.contentWindow.document.documentElement.scrollHeight;
return;
}else{
iframe.height = iframe.contentDocument.body.scrollHeight;
return;
}
}catch(e){
throw new Error('setIframeHeight Error');
}
};
/**
* 子级页面给父级页面元素设置高度
* @param id
* @returns
*/
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');
}
};
二、详细使用
<iframe id="socialHousingIframe" border="0" frameborder="0" scrolling="no"
width="100%" height="100%" style="padding: 0; margin: 0;"
src="../../static/analysis/socialHousing.html">
</iframe>
function thisIframeHeightAuto(){
setIframeHeight("socialHousingIframe");
};
$(function(){
//定时处理
window.setInterval("thisIframeHeightAuto()", 200);
//首次加载使用setIframeHeightAfterLoad,可以省略,由定时任务处理
setIframeHeightAfterLoad("socialHousingIframe");
});

(如果文章对您有所帮助,欢迎捐赠,^_^)
================================
©Copyright 蕃薯耀 2021-03-10
https://www.cnblogs.com/fanshuyao/
版权声明:本文为w995223851原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。