兼容各浏览器的iframe高度自适应
var ifobj = document.getElementById('iframe_link');
var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串
var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
function AutoHeight() { if (document.readyState != 'complete') { setTimeout(function() { AutoHeight(); }, 50); } else { try { //IE、fireFox下测试通过 //不能使用scrollHeight,因为在火狐和IE9中的高度与其它浏览器不同
if (isIE) {
ifobj.style.height = ifobj.contentWindow.document.body.offsetHeight + 0 + "px";
} else {
ifobj.style.height = ifobj.contentWindow.document.documentElement.offsetHeight + 0 + "px";
}
} //注意,别忘了加最后那个"px",不然fireFox下就不起作用了 //加的那0是为了让非IE浏览器高度不会一直增加 catch (e) {}
ifobj.style.visibility = "visible"; } } function stateChangeIE(_frame) { if (_frame.readyState == "complete") //state: loading ,interactive, complete { AutoHeight(); } } function stateChangeFirefox(_frame) { AutoHeight(); } ifobj.onreadystatechange = function() { stateChangeIE(this); }; ifobj.onload = function() { stateChangeFirefox(this); };
同时iframe元素如下:
<iframe id="iframe_link" scrolling="no" frameborder="0" src="http://jifen.le.com/" style="width: 100%; visibility:hidden;"></iframe>
scrolling="no"是必须要加的,否则页面会有滚动条。