A-A+
js中iframe载入后高度自适应
本文章分为两部份来介绍,一是介绍关于iframe载入完毕的判断介绍了关于iframe载入完成的判断,然后根据判断我再介绍载入完成后使iframe高度自适应.
关于iframe载入完毕的判断介绍了关于iframe载入完成的判断方法
iframe中跨域载入页面,在父级页面由于跨域的限制是访问不了加载页面的window对象,也就调用不了子页面中声明的函数。
因此在父级页面中判断iframe是否载入完毕最初的方式是使用参照元素载入完成的方式,代码如下:
- var loginiframe = document.createElement("iframe");
- loginiframe.src = "https://www.xiariboke.net/";
- loginiframe.onload = function(){
- alert("load");
- }
- document.body.appendChild(loginiframe);
但是上面这种方式在ie浏览器下在loginiframe加载完成后却没有响应,对ie浏览器做了其他的处理,代码如下:
- var isIE = navigator.userAgent.toLowerCase().indexOf("msie") > -1;
- var loginiframe = document.createElement("iframe");
- loginiframe.src = "http://login.hxsd.com/";
- if (isIE){
- loginiframe.onreadystatechange = function(){
- if (loginiframe.readyState == "complete"){
- alert("load");
- }
- };
- } else {
- loginiframe.onload = function(){
- alert("load");
- };
- }
- document.body.appendChild(loginiframe);
问题解决后,通过阅读《Iframes, onload, and document.domain》,在IE下对于iframe的onload的支持是隐性的,最终解决方式,代码如下:
- var loginiframe = document.createElement("iframe");
- loginiframe.src = "https://www.xiariboke.net/";
- if (loginiframe.attachEvent){
- loginiframe.attachEvent("onload", function(){
- alert("load");
- });
- } else {
- loginiframe.onload = function(){
- alert("load");
- };
- }
- document.body.appendChild(loginiframe);
下面是介绍载入完成后使iframe高度自适应.
具体的实现代码如下:
- function loadFrame(oFrame, sFrameSrc) {
- oFrame.src = sFrameSrc;
- if (oFrame.attachEvent){
- oFrame.attachEvent("onload", function(){
- autoChangeFrameHeight(oFrame);
- });
- } else {
- oFrame.onload = function(){
- autoChangeFrameHeight(this);
- };
- }
- }
- function autoChangeFrameHeight(oFrame) {
- var nHeight = Math.max(oFrame.contentWindow.document.body.scrollHeight, oFrame.contentWindow.document.documentElement.scrollHeight);
- oFrame.height = nHeight;
- }
以上方法只适用于同域的链接,在iframe内的内容加载完成后会获取iframe内的高度赋值给iframe的高度,对于跨域的情况,由于浏览器安全性的设置,不同域的页面之间是不能通信的,解决的方法是需要通过在iframe调用的页面中构建一个与父级页面同域的页面,通过url的形式将子页面的高度传递过去,具体代码如下:
- //子页面中:
- window.onload = function() {
- var oFrame = document.createElement("iframe");
- var nHeight = Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);
- document.body.appendChild(oFrame);
- oFrame.src = "http://PARENT_DOMAIN/agentFrame.html?height=" + nHeight;
- oFrame.style.display = "none";
- }
- //代理页面中:
- var nHeight = location.href.match(/?height=(d+)$/)[1];
- window.top.document.getElementById("frame").height = nHeight;
其中window.top为调用的最顶层窗口.