针对多个iframe的情况
iframe标签
<iframe width="100%" height="100%" src="/..."></iframe>
js代码
function iframeLoad() {
var ifms = document.getElementsByTagName("iframe"); //获取iframe
for (let index = 0; index < ifms.length; index++) {
let ifmItem = ifms[index];
if (ifmItem.attachEvent) { //判断为了兼容不同浏览器
ifmItem.attachEvent("onload", function () {
ifmItem.height = 0;
ifmItem.height = ifmItem.contentWindow.document.documentElement.scrollHeight;
});
} else {
ifmItem.onload = function () { //要在iframe加载后在去获取高度
ifmItem.height = 0;
ifmItem.height = ifmItem.contentDocument.body.scrollHeight;
};
}
}
}
注意要在页面元素加载完成后再去设置高度
本文介绍了一种使用JavaScript实现多个iframe自适应高度的方法。通过遍历页面上的所有iframe元素,并在加载完成后动态调整其高度,确保iframe能够完美适配其内容的高度。

1万+

被折叠的 条评论
为什么被折叠?



