iFrame高度自适应终极解决方案(兼容IE7,8,9 Firefox3.6+,Chrome 12+)
最近接手了一个web项目,由于一些很蛋疼的压力迫于无奈使用了iFrame来做页面布局,高度自适应问题自然就被提上台面儿了。在网上找了很多的解决办法无果,要么是干脆无效,要么是iframe首次加载的时候高度ok,用ajax加载几个元素高度撑大了以后就越界了。最后跟公司几个前端请教最终修成正果,闲话少说直接上代码
?
var frameHandler = function() {var inner;var iframeId = "";return inner = {_isSupport : false,init : function() {},create : function(frame) {iframeId=frame.id;frame.frameBorder = "none";frame.scrolling = "no";frame.style.marginTop = '40px';frame.contentWindow.focus();inner.check();if (inner._isSupport) {if (!frame.addEventListener) {frame.attachEvent("onload", function() {frame.detachEvent("onload", arguments.callee);inner.adjustFrameHeight();frame.contentWindow.attachEvent("onresize", inner.adjustFrameHeight);});} else {frame.addEventListener("load", function() {frame.removeEventListener('load', arguments.callee, false);inner.adjustFrameHeight();frame.contentWindow.document.documentElement.addEventListener('DOMSubtreeModified', inner.adjustFrameHeight, false);}, false);}} else if (frame.addEventListener) {// for FF 2, Safari 2, Opera 9.6+frame.addEventListener("load", function() {var fn = arguments.callee;setTimeout(function() {frame.removeEventListener('load', fn, false);}, 100);inner.adjustFrameHeight();frame.contentWindow.document.documentElement.addEventListener('DOMNodeInserted', inner.adjustFrameHeight, false);frame.contentWindow.document.documentElement.addEventListener('DOMNodeRemoved', inner.adjustFrameHeight, false);}, false);}},getFrame : function() {return document.getElementById(iframeId).contentWindow;},adjustFrameHeight : function() {var elem = document.getElementById(iframeId);elem.style.height = Math.max(elem.contentWindow.document.body.scrollHeight, elem.contentWindow.document.documentElement.scrollHeight) + 'px';},check : function() {var remain = 1, doc = document.documentElement, dummy;if (doc.addEventListener) {doc.addEventListener("DOMSubtreeModified", function() {inner._isSupport = true;doc.removeEventListener("DOMSubtreeModified", arguments.callee, false);}, false);} else {inner._isSupport = true;return ;}dummy = document.createElement("div");doc.appendChild( dummy );doc.removeChild( dummy );}}}();
?关键是对DOMSubtreeModified、DOMNodeInserted、DOMNodeRemoved这几个事件的监听,dom结构有变化的时候也可以自适应了。有需要的尽管拿去吧
附上一个示例(chrome下需要把页面放在apache之类的服务器上才能正常,其他的本地运行也ok)
?
?