iframe中有ajax,设置iframe自适应高度

-------------------------------------------------------------------

http://www.jb51.net/article/15780.htm

http://www.jb51.net/article/48936.htm

http://bestchenwu.iteye.com/blog/1231956

在iframe外添加此js,以下两个都可以

------------1----------------------------

function iFrameHeight() {
var ifm = document.getElementById("cateFrame");
var subWeb = document.frames ? document.frames["cateFrame"].document : ifm.contentDocument;
if (ifm != null && subWeb != null) {
ifm.height = subWeb.body.scrollHeight;
}
}

-----------2-----------------------

function SetWinHeight(obj) {
var win = obj;
if (document.getElementById) {
if (win && !window.opera) {
if (win.contentDocument && win.contentDocument.body.offsetHeight)
win.height = win.contentDocument.body.offsetHeight;
else if (win.Document && win.Document.body.scrollHeight)
win.height = win.Document.body.scrollHeight;
}
}
}

------iframe做些修改--------

onload 方法,可以写iFrameHeight()也可以写Javascript:SetWinHeight(this)

<iframe id="cateFrame" name="cateFrame" width="100%" frameborder="0" scrolling="no"
marginwidth="0" marginheight="0" src="welcome.aspx" onload="iFrameHeight()">
<%-- Javascript:SetWinHeight(this)--%>
</iframe>

----------------以下是有ajax的情况下使用的-------------------

在iframe页面内body后添加此js 再次设置一下iframe高度
<script type="text/javascript">
var iframeLoaded = function (iframe) {
if (iframe.src.length > 0) {
if (!iframe.readyState || iframe.readyState == "complete") {
var bHeight = iframe.contentWindow.document.body.scrollHeight;
var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max(bHeight, dHeight);
iframe.height = height;
}
}
}

//分页时重新设置 iframe 高度 ; 修改后:iframe.name = iframe.id
var reSetIframeHeight = function () {
//try {
var oIframe = parent.document.getElementById(window.name);
//oIframe.height = 80;
iframeLoaded(oIframe);
// }
// catch (err) {
// try {
// parent.document.getElementById(window.name).height = 500;
// } catch (err2) { }
// }
}

// reSetIframeHeight();


var sendcount = 0;
var completecount = 0;
// 添加ajax全局事件处理。
$(document).ajaxStart(function (a, b, c) {
}).ajaxSend(function (e, xhr, opts) {
sendcount++;
}).ajaxError(function (e, xhr, opts) {
}).ajaxSuccess(function (e, xhr, opts) {
}).ajaxComplete(function (e, xhr, opts) {
completecount++;
reSetIframeHeight();

}).ajaxStop(function () {
});

</script>

原文地址:https://www.cnblogs.com/jcz1206/p/3990934.html