Iframe设置动态高度仅适用于chrome

Iframe setting dynamic height works only on chrome

本文关键字:适用于 chrome 高度 设置 动态 Iframe      更新时间:2023-09-26

我在网页上使用iframe。我需要根据内容动态设置iframe的高度。我使用以下代码来实现这一点。

$('iframe').on('load',function(){
    $('iframe').attr('id','sop_iframe');
    $('#sop_iframe').height($('#sop_iframe').contents().height())   
});

这在铬合金中非常适用。。但在firefox和IE上没有。有任何跨浏览器的jquery解决方案吗??

function setFrameHeight() { 
var h;
var defaulth = 150;
var scrollh = window.top.document.documentElement.scrollTop;
//reset the iframe to default height
window.top.document.getElementById("iframe_form").height = defaulth;
//get actual heights
var y1 = document.documentElement.scrollHeight;
if (y1 < document.body.scrollHeight) y1 = document.body.scrollHeight;
var y2 = document.documentElement.offsetHeight;
if (y2 < document.body.offsetHeight) y2 = document.body.offsetHeight;
h = (y1 > y2) ? y1 : y2;
//determine smaller heights
h = (h > defaulth) ? h : defaulth;
//set "iframe_form" to proper height
window.top.document.getElementById("iframe_form").height = h;

//scroll to top
window.top.scrollTo(0,scrollh);
}