注意:这两种方式不支持跨域使用
1.jQuery简单实现iframe的高度根据页面内容自适应的方法(加载后展示使用)
方式1:
//注意:下面的代码是放在和iframe同一个页面中调用
$("#iframeId").load(function () {
var mainheight = $(this).contents().find("body").height() + 30;
$(this).height(mainheight);
});
方法2:
//注意:下面的代码是放在iframe引用的子页面中调用
$(window.parent.document).find("#iframeId").load(function () {
var main = $(window.parent.document).find("#iframeId");
var thisheight = $(document).height() + 30;
main.height(thisheight);
});
2.原生自适应方式
<iframe id="mainFrame" name="mainFrame" scrolling="no" src="Index.aspx"frameborder="0" style="padding: 0px; width: 100%; height: 1000px;"></iframe>
<script type="text/JavaScript"> startInit('mainFrame', 560);</script>
js
var browserVersion = window.navigator.userAgent.toUpperCase();
var isOpera = false, isFireFox = false, isChrome = false, isSafari = false, isIE = false;
function reinitIframe(iframeId, minHeight) {
try {
var iframe = document.getElementById(iframeId);
var bHeight = 0;
if (isChrome == false && isSafari == false)
bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = 0;
if (isFireFox == true)
dHeight = iframe.contentWindow.document.documentElement.offsetHeight + 2;
else if (isIE == false && isOpera == false)
dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
else if (isIE == true && ! -[1, ] == false) { } //ie9+
else
bHeight += 3;
var height = Math.max(bHeight, dHeight);
if (height < minHeight) height = minHeight;
iframe.style.height = height + "px";
} catch (ex) { }
}
function startInit(iframeId, minHeight) {
isOpera = browserVersion.indexOf("OPERA") > -1 ? true : false;
isFireFox = browserVersion.indexOf("FIREFOX") > -1 ? true : false;
isChrome = browserVersion.indexOf("CHROME") > -1 ? true : false;
isSafari = browserVersion.indexOf("SAFARI") > -1 ? true : false;
if (!!window.ActiveXObject || "ActiveXObject" in window)
isIE = true;
window.setInterval("reinitIframe('" + iframeId + "'," + minHeight + ")", 100);
}