DIV CSS 佈局教程網

用 iframe 加載外部網頁並自適應高度
編輯:JavaScript綜合知識     

有些時候需要在不跳轉的前提下,把另一個站點的內容嵌到自己頁面裡,iframe 是最直接的方案。實戰中的關鍵細節是:如何讓 iframe 的高度自動適應窗口,避免出現雙重滾動條。

實現代碼

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>iframe 加載外部頁面</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
  window.onerror = function () { return true; };

  $(function () {
    var headerH = 0;                       // 頂部佔用高度,按需調整
    var h = $(window).height();

    // 讓 iframe 高度 = 視窗高度 - 頂部佔用
    $("#huoduan_frame").height((h - headerH) + "px");
  });
</script>
</head>
<body scroll="no" style="margin:0; padding:0; overflow-y:hidden">
  <iframe id="huoduan_frame" frameborder="0" scrolling="yes" name="main"
          src="https://www.example.com/index.htm"
          style="height:500px; width:100%; z-index:1; overflow:visible;">
  </iframe>
</body>
</html>

要點說明

高度計算。用 $(window).height() 拿到視窗高度,減去頭部導航等佔用空間,就是 iframe 應有的高度。若頁面有可伸縮的頭部,應在 resize 事件裡重新計算。

滾動條策略。示例把 body 的滾動去掉(overflow-y: hidden),只保留 iframe 自身的 scrolling="yes",這樣頁面只有一層滾動,體驗更乾淨。

窗口尺寸變化時同步。示例只處理了初始加載,實戰中建議補上:

$(window).resize(function () {
  $("#huoduan_frame").height($(window).height() - headerH);
});

跨域限制必須了解

如果嵌入的是不同源的頁面,出於同源策略,父頁面無法讀取 iframe 內部的 document,也就拿不到它的實際內容高度,「自適應內容高度」這一點做不到。此時只能像示例那樣按視窗高度鋪滿。

若兩個頁面同源,可以這樣讓 iframe 高度完全貼合內容:

$('#myFrame').load(function () {
  var height = $(this).contents().find("body").height();
  $(this).height(height);
});

跨域且雙方可控時,正規做法是通過 postMessage 讓子頁面把自身高度告訴父頁面,父頁面再調整。這也是嵌入第三方內容(支付頁、評論組件)時的通用方案。

另外提醒一點:被嵌入的站點可能通過 X-Frame-Options 或 CSP 的 frame-ancestors 響應頭拒絕被嵌套,此時 iframe 會顯示空白,這是服務端的安全策略,前端無法繞過。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved