layui实现iframe高度自适应代码教程
html代码如下:
<div style="padding: 15px;">
<iframe src="jinhei.html" name="right" width=100% id="myiframe" onload="setHeight()" height="1" scrolling="no"
frameborder="0"></iframe>
<br><br>
</div>
javascript核心代码如下:
function getIframeWindow(obj) {
return obj.contentWindow || obj.contentDocument.parentWindow;
}
function getIframeHeight(obj){
var idoc = getIframeWindow(obj).document;
if(idoc.body){
return Math.max(idoc.body.scrollHeight,idoc.body.offsetHeight);
}else if(idoc.documentElement){
return Math.max(idoc.documentElement.scrollHeight,idoc.documentElement.offsetHeight);
}
}
function setHeight(){
var myiframe = document.getElementById("myiframe");
myiframe.height = getIframeHeight(myiframe)+ 30;
}