解決iframe高度自適應各種方法

來源:互聯網
上載者:User

今天幫一哥們的女朋友的親戚整個網站,用的dedecms弄的,有段時間沒接觸dede了,感覺有點生疏,不過還好網站功能一般,所以花了半天時間給整出來了。在最後,由於該cms的留言板模組是獨立出來的,我為了省事,就在一個頁面用了iframe直接引用留言板的頁面進來,可問題就出現了,就是高度不能自適應,給它定死高度吧,不太靈活,於是在網上搜了下iframe自適應高度的解決方案,搜了很多都是N年前的資訊,有些早已不起作用了。但功夫不負有心人,最後還是讓我找到了這個解決辦法,僅在此記錄一下吧!

 代碼如下 複製代碼

<iframe id="frame_content" src="guestbook.php" scrolling="no" width="950" frameborder="0" onload="this.height=100"></iframe>
 
<script type="text/javascript">
    function reinitIframe () {
        var iframe = document.getElementById("frame_content");
        try{
            var bHeight = iframe.contentWindow.document.body.scrollHeight;
            var dHeight = iframe.contentWindow.document.documentElement.scrollHeight;
            var height = Math.max(bHeight, dHeight);
            iframe.height =  height;
        }catch (ex){}
    }
    window.setInterval("reinitIframe()", 200);
</script>

今天拓源給大家分享iframe自適應高度的方法。


iframe的寬度預設為300px,高度預設為150px,如果需要自適應高度,則需要使用以下代碼:

需要注意的是,frameresize()方法必須放置在iframe代碼的後面,否則無效。

 代碼如下 複製代碼

<iframe id="iframepage" name="iframepage" width="100%" height="100%" src="http://www.111cn.net/" allowTransparency="true" style="border:none; overflow-x:none;" scrolling="auto"></iframe>
<script type="text/javascript" src="jquery.js"></script>
<script language="javascript">
    function frameresize(){
        var winheight = $(window).height();
        var iframeheight = winheight;
        $('#iframepage').css('height', iframeheight + 'px');
    };
                                     
    if(window.attachEvent){
        document.getElementById("iframepage").attachEvent('onload', frameresize);
    }
    else{
        document.getElementById("iframepage").addEventListener('load', frameresize, false);
    }
                                     
    $(window).resize(frameresize);
    frameresize();
</script>

以上iframe代碼為調用拓源網旗下網站烏龍貓的首頁,可以看到iframe高度自適應

聯繫我們

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