首頁  >  文章  >  web前端  >  關於iframe嵌套 子頁面(含iframe)自動擴高的詳解

關於iframe嵌套 子頁面(含iframe)自動擴高的詳解

黄舟
黄舟原創
2017-07-24 09:23:373275瀏覽

公司網站後台原本不是用iframe設計的,後來為了節省資源,經過討論決定把網站後台改成iframe。 iframe可以實現和ajax相似的局部刷新的效果(他們的實現原理是不同的),iframe雖然很強大,但其不能根據子頁面的高度自動擴高,這點很惱人啊,於是我在網上搜了搜,找到以下幾種方法,然後進行部分改進了。

一、jquery取得(注意:此種方法只適合父類別頁面和子類別頁面在同一個網域下,且子類別頁不能包含iframe)

aa.html(父及頁)

<iframe name="rightcontent"  id="rightcontent" src=&#39;bb.html&#39; frameborder="0" width="100%" scrolling="no"></iframe>

$("#rightcontent").load(function(){
       var mainheight = $(this).contents().find("body").height()+30;
       $(this).height(mainheight);
    });

二、用js取得(網上js獲得的方法很多,隨便一搜就可以找到,但要注意的是:子類頁不能包含iframe,如果子類頁中有ifrme ,還是無法實現自動擴高的效果的)

function SetCwinHeight(obj) {
    var cwin = obj;
    if (document.getElementByIdx_x_x_x) {       
      if (cwin && !window.opera) {
            if (cwin.contentDocument && cwin.contentDocument.body.offsetHeight){
               cwin.height = cwin.Document.body.offsetHeight + 30;
               alert(cwin.height); //FF NS
            }else if (cwin.Document && cwin.Document.body.scrollHeight){
                cwin.height = cwin.Document.body.scrollHeight + 10;
            } //IE
        }else {
            this.height=rightcontent.document.body.scrollHeight+30
            if (cwin.contentWindow.document && cwin.contentWindow.document.body.scrollHeight)
                cwin.height = cwin.contentWindow.document.body.scrollHeight; //Opera
        }
    }
}

<iframe name="rightcontent"  id="rightcontent" src=&#39;bb.html&#39; frameborder="0" width="100%" scrolling="no" onload="SetCwinHeight(this)">
</iframe>

三、支援子類別頁面中包含iframe,即iframe嵌套使用(火狐和ie測試,其他瀏覽器還沒測試)

 <iframe name="rightcontent"  id="rightcontent" src=&#39;bb.html&#39; frameborder="0" width="100%" scrolling="no" onload="this.height=rightcontent.document.body.scrollHeight+50"></iframe>

四、這個是補充的,網站用了方法三,但是發現如果如果牽扯到跨域名了,方法三不起作用了,是因為我在子頁面中寫了ef4bb24a672a2283c083e2b0595919d1document.domain = 'xxx.com';2cacc6d41bbb37262a98f745aa00fbf0,這種情況下怎麼辦呢,程式碼如下:

在子頁面中

<script type="text/javascript">
//设置域信息
document.domain = &#39;xxx.com&#39;;
//设置父级页面引用自身的iframe高度
function setHeight(){
  //判断是否为顶级页面
  if(window.top!=window.self){
      parent.document.getElementByIdx_x(&#39;rightcontent&#39;).height=document.body.scrollHeight+20
  }
}
setHeight();
</script>

以上是關於iframe嵌套 子頁面(含iframe)自動擴高的詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn