JQuery實現跨域IFrame自動高度方案

來源:互聯網
上載者:User

由於項目中引入了JQuery,不方便再引用YUI。所以依照 Session variables without cookies 原理 ,直接用JQuery實現如下:

情境:首頁面 (emo_windowname.html)一個IFrame(framePreview), 在頁面載入或者單擊按鈕時,讓IFrame載入一個頁面(http://...../本文.html).

條件:正 文.html 預告加入指令碼,或者使用HttpModule加入指令碼:

$(function(){
     window.name = document.body.scrollHeight;

});

這樣,在首頁面中,就 可以通過window.name把高度取過來,然後設定一下 framePreview的高度。

代碼如下:

主 頁面代碼

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"  "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF- 8">
<title>跨域IFrame自動高度</title>
<script  language="javascript" src="../Library/jquery-1.3.2.min.js"  type="text/javascript"></script>
<script  type="text/javascript">

    function autoHeightIFrameNavigate (iframeId,url)
    {
        var iframe = $('#' +  iframeId);
        iframe.attr('_name_',iframe.attr('name'))     //備份原來的 name
        .attr('src',url)                             //設定URL
        .one ('load',function () {
            this.contentWindow.location =  "about:blank";    //導向代理頁面,我直接使用了這個
             $(this).one('load',function () {
                var msg  = this.contentWindow.name;            //得到值 這個值就是高度了
                 this.contentWindow.name = $(this).attr('_name_');     //恢複原來的 Name
                this.contentWindow.location =  url;            //再次導向目標頁面

                 try
                {
                    var  height = eval(msg);                    //得到並設定高度
                     alert(height);
                     iframe.css('height', height + 'px');

                 }
                catch(e)
                 {
                    alert('目標頁面沒有設定高度到  window.name')
                }

             })

        
        })
    }
     $(function () {
        $('#btnNavigator').click(function(){
             autoHeightIFrameNavigate('iframePreview',  $('#tbUrl').val());
        });

    })

</script>

</head>
<body>
    <input  type="text" id="tbUrl" style="width:100%"  NAME="tbUrl" value="http://10.120.147.47/FileUp/e8aa5d05-c682-4913-8f57- f49d0c6e01b5/html/%e6%ad%a3%e6%96%87.html"/>
    <input  type="button" id="btnNavigator" id="btnNavigator"  value="轉到" />
    <p>
        在ie 7, firfox  3.0.10 測試通過。
    </p>
    <div>
         <iframe id="iframePreview"    style="width: 100%;height:800px;"  scrolling="no" frameborder="no"></iframe>
     </div>


</body>
</html>

聯繫我們

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