Js動態獲取iframe子頁面的高度////////////////////////zzzz

Js動態獲取iframe子頁面的高度

 

Js動態獲取iframe子頁面的高度總結javascript

問題的原因

產品有個評論列表引用的是個iframe,高度不固定因而引起這個總結。html

方法1:父級頁面獲取子級頁面的高度 給元素設置高度

這方法是用在父級頁面裏的,經過獲取子級頁面的高度給iframe設置高度java

涉及了一些兼容問題:跨域

IE用attachEvent | 3C用onload來判斷子頁面是否加載完成。緩存

IE用contentWindow | 3C用contentDocument來獲取子頁面安全

IE用document.documentElement.scrollHeight(兼容ie6 ie7)| 3C用body.scrollHeight獲取頁面高度dom

function setIframeHeight(id){  try{   var iframe = document.getElementById(id);   if(iframe.attachEvent){    iframe.attachEvent("onload", function(){     iframe.height = iframe.contentWindow.document.documentElement.scrollHeight;    });    return;   }else{    iframe.onload = function(){     iframe.height = iframe.contentDocument.body.scrollHeight;    };    return;   }  }catch(e){   throw new Error('setIframeHeight Error');  } }

方法2:子級頁面給父級頁面元素設置高度

這方法是用在子級頁面裏的,經過獲取子級頁面的高度給父級iframe設置高度spa

子級頁面經過parent獲取父級iframe 給iframe設置高度,兼容同方法1。htm

缺點是刷父級頁面時iframe有緩存,需求清理緩存才能生效。blog

function setParentIframeHeight(id){  try{   var parentIframe = parent.document.getElementById(id);   if(window.attachEvent){    window.attachEvent("onload", function(){     parentIframe.height = document.documentElement.scrollHeight;    });    return;   }else{    window.onload = function(){     parentIframe.height = document.body.scrollHeight;    };    return;   }  }catch(e){   throw new Error('setParentIframeHeight Error');  } }

須要注意的跨域操做

若是兩個頁面有一種狀況,兩個子域名:

 

aaa.xxx.com

bbb.xxx.com

須要將兩個頁面都設置如:

document.domain ="xgo.com.cn";

這樣這兩個頁面就能夠互相操做了。也就是實現了同一基礎域名之間的"跨域"。

利用document.domain實現跨域:

前提條件:這兩個域名必須屬於同一個基礎域名!並且所用的協議,端口都要一致,不然沒法利用document.domain進行跨域

Javascript出於對安全性的考慮,而禁止兩個或者多個不一樣域的頁面進行互相操做。

相同域的頁面在相互操做的時候不會有任何問題。

相關文章
相關標籤/搜索