js 跨域IFRAME自適應高度例子

來源:互聯網
上載者:User


需求: A頁面使用iframe標籤跨域包含B頁面
問題: A/B頁面不同域,A頁面無法擷取並自適應B頁面高度
方案: 增加C頁面,A/C頁面同域,A包含B,B包含C,B通知C高度,C調整A頁面iframe高度~
 
跨域IFRAME自適應高度
 
A頁面:

<iframe id="iframe_a" src="B頁面url" width="100%" style="border:0"></iframe>


B頁面:

<div style="background:#9AC86C;height:1000px"></div>
<iframe id="iframe_b" src="C頁面url" style="display:none"></iframe>


<script>
    //擷取本頁面高度
    var height_b = Math.max(document.body.scrollHeight, document.body.clientHeight);
    //在src屬性中增加高度資訊
    var iframe_b = document.getElementById('iframe_b');
    iframe_b.src = iframe_b.src + '#' + height_b;
</script>


C頁面:

<script>
    //擷取B頁面高度
    var height_b = window.location.hash.split('#')[1] + 'px';
    //擷取A頁面iframe對象
    var iframe_a = parent.parent.document.getElementById('iframe_a');
    //調整A頁面iframe高度
    iframe_a.height = height_b;
</script>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.