<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          6種iframe高度自適應的方法

          共 8552字,需瀏覽 18分鐘

           ·

          2021-03-14 14:11

          js自適應高度,實際上就是設置iframe的高度,設置等于內(nèi)嵌網(wǎng)頁的高度,從而看不到滾動條和嵌套痕跡。對于用戶體驗和網(wǎng)站美觀起著重要作用。我們可以通過css來給它直接定義一個高度,同樣可以實現(xiàn)上面的需求。當內(nèi)容是未知或者是變化的時候。這個時候又有幾種情況了。

          1、iframe內(nèi)容未知,高度可預測

          這個時候,我們可以給它添加一個替換的css的min-height值,然后同時使用JavaScript改變高度。常用的兼容代碼有:
          // document.domain = "caibaojian.com";function setIframeHeight(iframe) {if (iframe) {var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;if (iframeWin.document.body) {iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;}}};
          window.onload = function () {setIframeHeight(document.getElementById('external-frame'));};

          如果在同一個頂級域名下,不同子域名之間互通信息,設置document.domain =“ caibaojian.com”只要修改以上的iframe的ID就可以了。不污染html代碼,建議使用上面的代碼。

          <iframe src="backtop.html" frameborder="0" scrolling="no" id="external-frame" onload="setIframeHeight(this)"></iframe>

          2、多個iframe的情況下

          <script language="JavaScript">//輸入你希望根據(jù)頁面高度自動調(diào)整高度的iframe的名稱的列表//用逗號把每個iframe的ID分隔. 例如: ["myframe1", "myframe2"],可以只有一個窗體,則不用逗號。//定義iframe的IDvar iframeids=["test"];//如果用戶的瀏覽器不支持iframe是否將iframe隱藏 yes 表示隱藏,no表示不隱藏var iframehide="yes";function dyniframesize(){var dyniframe=new Array()for (i=0; i<iframeids.length; i++){if (document.getElementById){//自動調(diào)整iframe高度dyniframe[dyniframe.length] = document.getElementById(iframeids[i]);if (dyniframe[i] && !window.opera){dyniframe[i].style.display="block";if (dyniframe[i].contentDocument && dyniframe[i].contentDocument.body.offsetHeight) //如果用戶的瀏覽器是NetScapedyniframe[i].height = dyniframe[i].contentDocument.body.offsetHeight;else if (dyniframe[i].Document && dyniframe[i].Document.body.scrollHeight) //如果用戶的瀏覽器是IEdyniframe[i].height = dyniframe[i].Document.body.scrollHeight;}}//根據(jù)設定的參數(shù)來處理不支持iframe的瀏覽器的顯示問題if ((document.all || document.getElementById) && iframehide=="no"){var tempobj=document.all? document.all[iframeids[i]] : document.getElementById(iframeids[i]);tempobj.style.display="block";}}}if (window.addEventListener)window.addEventListener("load", dyniframesize, false);else if (window.attachEvent)window.attachEvent("onload", dyniframesize);elsewindow.onload=dyniframesize;</script>

          3、針對知道的iframe的ID調(diào)用

          function iframeAutoFit(iframeObj){setTimeout(function(){if(!iframeObj) return;iframeObj.height=(iframeObj.Document?iframeObj.Document.body.scrollHeight:iframeObj.contentDocument.body.offsetHeight);},200)}

          4、內(nèi)容寬度變化的iframe高度自適應

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

          5、跨域下的iframe自適應高度

          跨域的時候,由于js的同源策略,父頁面內(nèi)的js無法獲取到iframe頁面的高度。需要一個頁面來做代理。方法如下:假設www.a.com下一個一個頁面a.html要包含我們使用www.a.com下一個另一個頁面agent.html來做代理,通過它獲取iframe頁面的高度,并設置iframe元素的高度。html中包含iframe:

          <iframe src="http://www.b.com/c.html" id="Iframe" frameborder="0" scrolling="no"></iframe>

          在c.html中加入如下代碼:

          <iframe id="c_iframe"  height="0" width="0"  src="http://www.a.com/agent.html" ></iframe><script type="text/javascript">(function autoHeight(){var b_width = Math.max(document.body.scrollWidth,document.body.clientWidth);var b_height = Math.max(document.body.scrollHeight,document.body.clientHeight);var c_iframe = document.getElementById("c_iframe");c_iframe.src = c_iframe.src + "#" + b_width + "|" + b_height;  // 這里通過hash傳遞b.htm的寬高})();</script>

          最后,agent.html中加入一段js:

          <script type="text/javascript">var b_iframe = window.parent.parent.document.getElementById("Iframe");var hash_url = window.location.hash;if(hash_url.indexOf("#")>=0){var hash_width = hash_url.split("#")[1].split("|")[0]+"px";var hash_height = hash_url.split("#")[1].split("|")[1]+"px";b_iframe.style.width = hash_width;b_iframe.style.height = hash_height;}</script>

          agent.html從URL中獲得寬度值和高度值,并設置iframe的高度和寬度(因為agent.html在www.a.com下,所以操作a.html時不受JavaScript的類似限制)

          6、postMessage + window.name實現(xiàn)跨域iframe高度自適應兼容版

          我們知道HTML5 PostMessage不支持IE8以下的瀏覽器跨域,于是我想到了window.name支持ie6和ie7的方案,那么能否把這兩種合并起來,變成一種全兼容的跨域方案呢?還別說,真有人能做到。

          html5 postMessage實現(xiàn)跨域

          postMessage是html5的一個新功能,可以實現(xiàn)不同域名之間的通信,通過給postMessage方式發(fā)送數(shù)據(jù),監(jiān)聽則通過在父子窗口上添加onmessage事件進行。缺點也就很明顯了,只有支持html5的瀏覽器才支持這種跨域方式,像IE6、7當然就拒之門外了!

          window.name實現(xiàn)跨域

          window.name實現(xiàn)跨域也是一個比較老的問題,之前kejun寫過一個演示,可是給的卻是同域名的通信。其實kejun的實例中就是實現(xiàn)跨域的,不過他采用了同一個域名,而且過程比較崎嶇:

          1. 建立iframe,指定src為被跨域的頁面

          2. 被跨域文件修改window.name,將數(shù)據(jù)傳給window.name

          3. 將iframe.src修改為本域代理文件,然后就可以取到contentWindow.name

          4. 進行處理數(shù)據(jù),清除iframe充分的運用了window.name因為頁面的URL改變而名稱不改變的特性。但是如果我們是自己用,還是可以的,而如果我們放出去要別人使用我們寫的東西,那樣學習成本太大。

          多瀏覽器雙向跨域

          為了解決上面的問題,我們使用的方法就是如果支持postMessage的瀏覽器就使用postMessage,如果不支持的就采用window.name的方式,幸運的是在IE6、7中支持跨域設置window.name,而我們就可以簡單的通過window.name來跨域。

          然后建立計時器來監(jiān)聽window.name是否發(fā)生了變化,如果變化則接收并分析window.name,然后做請求。 

          演示和代碼

          <body>  <div style="width:100%;border:1px solid green;">    <h3>this page from :<span id="host"></span></h3>    <input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button>  </div>    <iframe id="iframeA" src="http://1.qdemo.sinaapp.com/cross-domain/client.html" style="border:1px solid #ff6600;width:100%;height:300px;"></iframe>  <script type="text/javascript">    document.getElementById('host').innerHTML = location.host;    function send(){      var val = document.getElementById('data').value;      sendMessage(val);    }    (function(win, doc){      var ifr = doc.getElementById('iframeA').contentWindow;      var cb = function(json){        alert(location.host+" get msg:"+json);      };      var sendMessage = function(){        if(win.postMessage){          if (win.addEventListener) {                    win.addEventListener("message",function(e){            cb.call(win,e.data);          },false);                }else if(win.attachEvent) {                    win.attachEvent("onmessage",function(e){            cb.call(win,e.data);          });                }          return function(data){            ifr.postMessage(data,'*');          };        }else{          var hash = '';                    setInterval(function(){                      if (win.name !== hash) {              hash = win.name;              cb.call(win, hash);            }          }, 50);          return function(data){            ifr.name = data;          };        }      };      win.sendMessage = sendMessage();    })(window, document);</script></body>
          <body>  <h3>this page from :<span id="host"></span></h3>  <input type="text" value="" id="data" /><button id="btn" onclick="send();">提交</button>  <ul>    <li>firefox、chrome等高級瀏覽器采用html5 postMessage方法</li>    <li>IE6 7等使用window.name方法</li>    <li>支持雙向跨域,在chrome 13、firefox6、IE6+測試通過</li>    <li>window.name可以通過data加隨機數(shù)方式,避免兩次提交的數(shù)據(jù)相同,本例沒做處理,所以如果不改變value值點擊提交是不會觸發(fā)alert的</li>    <li><a href="cross-domain.zip">demo下載</a></li>  </ul>  <script type="text/javascript">    document.getElementById('host').innerHTML = location.host;    function send(){      var val = document.getElementById('data').value;      sendMessage(val);    }    (function(win, doc){      var ifr = win.parent;            var cb = function(json){        alert(location.host+"  get msg:"+json);      };      var sendMessage = function(){        if(win.postMessage){          if (win.addEventListener) {                    win.addEventListener("message",function(e){            cb.call(win,e.data);          },false);                }else if(win.attachEvent) {                    win.attachEvent("onmessage",function(e){            cb.call(win,e.data);          });                }
          return function(data){ ifr.postMessage(data,'*'); }; }else{ var hash = ''; setInterval(function(){ if(win.name!==hash){ hash = win.name; cb.call(win,hash); } },50); return function(data){ ifr.name = data; }; } } win.sendMessage = sendMessage(); })(window, document);</script></body>

          基于上面的代碼,結合我上篇文章的演示,我們再來命名一個iframe自適應高度的解決方案。


          本文完?


          瀏覽 78
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  边添小泬边狠狠躁.樱桃 | 黄色视频日本 | 亚洲国产日韩在线一区 | 欧美艹逼网 | 91内射|