iframe通信問題及自適應高度

前言:最近在編寫html5-handbook時遇到ifarme自適應高度問題,查看了衆多技術大牛的博文,在此總結如下:

iframe通信問題(服務器端訪問)

iframe同域通信

  • 實例主頁面調用iframe頁面函數
    主頁面
<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>frame自適應高度</title>
</head>
<body>
    <div id="test">我是主頁面</div>    
    <iframe src="iframe.html" id="iframe" width="100%" frameborder="0"></iframe>
<script type="text/javascript">
    function A(){
        alert("A");
    }
    //iframe加載完畢執行回調函數
    function iframeIsLoad(iframe,callback){
        if(iframe.attachEvent){
            iframe.attachEvent('onload',function(){
                callback && callback();
            });
        }else{
            iframe.onload = function(){
                callback && callback();
            }
        }
    }
    var iframe = document.getElementById('iframe');
    iframeIsLoad(iframe,function(){
        var object = document.getElementById('iframe').contentWindow;
        object.b();
    });
</script>
</body>
</html>

iframe頁面

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>frame自適應高度</title>
</head>
<body> 
<p>我是iframe<p>  
<script type="text/javascript">
    function b(){
        alert("b");
    }
    self.parent.A();
    alert(self.parent.document.getElementById("test"));
</script>
</body>
</html>
  • 通過子頁面操作父頁面
    執行函數:self.parent.A()
    獲取元素:self.parent.document.getElementById(“id”);
    執行順序顯而易見!

iframe跨域通信

本人知識有限,暫不討論

iframe自適應高度

同域自適應高度

方法一思路:在iframe頁面獲取被嵌套iframe元素,通過JavaScript取得被嵌套頁面最終高度;調用主頁面函數進行設置iframe高度
注意
iframe頁面獲取高度,本人在這範二了;不過即使發現。頁面高度參考
主頁面

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>frame自適應高度</title>
</head>
<body>
    <div id="test">我是主頁面</div>    
    <iframe src="iframe1.html" id="iframe" width="100%"></iframe>
<script type="text/javascript">
    function iframeAutoHeight(height){
        var iframe = document.getElementById("iframe");
        iframe.style.height = height + "px";
    }
</script>
</body>
</html>

iframe頁面

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8' />
    <title>frame自適應高度</title>
</head>
<body> 
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
<p>我是iframe<p>  
</body>
<script type="text/javascript">
    var iframeBodyHeight = document.body.scrollHeight;
    self.parent.iframeAutoHeight(iframeBodyHeight);
</script>
</html>

方法二思路:在iframe頁面獲取自身document.body.scrollHeight函數;回調函數進行設置iframe高度
時間有限,方法二代大家可以自己試試

跨域自適應高度

本人知識有限,暫不討論

參考:
龍恩0707
代碼:
Aidan Dai

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章