欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

iframe根据子界面高度自适应的情况

程序员文章站 2022-07-01 23:03:36
iframe根据子界面高度自适应的情况--子界面table异步 iframe //set iframe height // 计算页面的实际高度,iframe自适应会用到 window.onload=...
iframe根据子界面高度自适应的情况--子界面table异步

iframe

//set iframe height

// 计算页面的实际高度,iframe自适应会用到

window.onload=function(){

function calcpageheight(doc) {

var cheight = math.max(doc.body.clientheight, doc.documentelement.clientheight,doc.body.offsetheight)

var sheight = math.max(doc.body.scrollheight, doc.documentelement.scrollheight,doc.body.offsetheight)

var height = math.max(cheight, sheight);

return height

}

//根据id获取iframe对象

var ifr = document.getelementbyid('mainframe')

ifr.onload = function() {

//解决打开高度太高的页面后再打开高度较小页面滚动条不收缩

ifr.style.height='0px';

var idoc = ifr.contentdocument || ifr.document

var height = calcpageheight(idoc)

console.log(height)

if(height < 850){

height = 850;

}

ifr.style.height = height + 'px'

}

}

但是后来发现部分界面,尤其是带有table的界面显示不全,iframe获取的高度比实际的要小.排查原因后发现,是界面在加载时,table的内容onload时没有获取到全部内容的高度,tbody为空.所以高度变小了.最后在同事的帮助下,通过以下代码解决了这个问题

//set iframe height

// 计算页面的实际高度,iframe自适应会用到

function calcpageheight(doc) {

var cheight = math.max(doc.body.clientheight, doc.documentelement.clientheight,doc.body.offsetheight)

var sheight = math.max(doc.body.scrollheight, doc.documentelement.scrollheight,doc.body.offsetheight)

var height = math.max(cheight, sheight);

return height

}

//根据id获取iframe对象

window.onload=function(){

var ifr = document.getelementbyid('mainframe');

ifr.onload=function(){

ifr.style.height='0px';

settimeout(function(){ //延时获取iframe里面的内容,是datatable数据加载完毕再获取dom里面 的元素高度

var idoc = ifr.contentdocument || ifr.document

var height =calcpageheight(idoc);

console.log(height);

if(height < 850){

height = 850;

}

ifr.style.height = height + 'px'

},1000);

}

}

具体逻辑是,需要延迟的获取iframe里面dom元素的高度

通过改进后,界面都能显示完整了.以此记录以下,希望能帮助大家