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

來源:互聯網
上載者:User

標籤:style   class   blog   code   java   color   

問題的緣由

產品有個評論列表引用的是個iframe,高度不固定於是引發這個總結。

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

這方法是用在父級頁面裡的,通過擷取子級頁面的高度給iframe設定高度

涉及了一些相容問題:

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

IE用contentWindow | 3C用contentDocument來擷取子頁面

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

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設定高度

子級頁面通過parent擷取父級iframe 給iframe設定高度,相容同方法1。

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

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出於對安全性的考慮,而禁止兩個或者多個不同域的頁面進行互相操作。
相同域的頁面在相互操作的時候不會有任何問題。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.