zl程序教程

您现在的位置是:首页 >  其它

当前栏目

解决iframe高度自适应

解决 高度 适应 iframe
2023-06-13 09:15:15 时间

大家好,又见面了,我是你们的朋友全栈君。

解决iframe高度自适应

原因

iframe的高度不会随着页面高度的变化而变化,可能会导致页面显示不全,或者页面下方有空白的问题。

第一种方法

这个方式更适用于嵌套的页面,当嵌套多个iframe时,比如左侧有个侧边栏,右侧是个大的iframe,这个大的iframe又嵌套了一层:中间是iframe,但是右侧又有个侧边栏,这时候不想让iframe单独滑动(避免页面出现两个滚动条),而是想整个页面一起滑动时,用这个方法。

html代码: 注意一定要写height=‘100%’ scrolling=‘no’ width=’100%’ 否则iframe会自己滑动

 <div class=" iframe My-home embed-responsive embed-responsive-16by9" id="taskheight">
        <iframe class="embed-responsive-item" frameborder="0" height='100%' id="form-iframe" name="formIframe" scrolling="no" width='100%'></iframe>
 </div>

js代码:

try { 

var timer;
$("#form-iframe").load(function () { 

if (timer) { 

clearInterval(timer);
}
//pre_height用于记录上次检查时body的高度
//mainheight用于获取本次检查时body的高度,并赋予iframe的高度
var mainheight, pre_height;
var frame = $(this);
timer = setInterval(function () { 

mainheight = $(document.body).height() + 10;
if (mainheight != pre_height) { 

pre_height = mainheight;
frame.height(Math.max(mainheight, 350));
}
}, 500);//每0.5秒检查一次
});
} catch (e) { 

}

第二种方法

这个方法更简单些,适用于左侧有个侧边栏,右侧是iframe,并且iframe可以自己滑动,只在页面高度变化时重新赋值即可。

html代码:

<div class="iframe My-home embed-responsive embed-responsive-16by9">
<iframe class="embed-responsive-item" frameborder="0" id="form-iframe" src=""></iframe>
<!--src是动态赋值的-->
</div>

js代码:

  //根据ID获取iframe对象
var org = $("#form-iframe")
org.onload = function () { 

//解决打开高度太高的页面后再打开高度较小页面滚动条不收缩
org.style.height = '0px';
var iDoc = org.contentDocument || org.document
var height = calcPageHeight(iDoc)
if (height < 850) { 

height = 850;
}
org.style(height, height + 'px')
}

两种方法我都用了,亲测好用!!!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/210442.html原文链接:https://javaforall.cn