iframe 最惱人的地方就是高度:設定了 scrolling="no" 時,內容一旦超出就被硬生生切掉;開著捲軸又顯得笨重。理想的做法是讓 iframe 依內容自動長高。
function adjustIFramesHeightOnLoad(iframe) {
var iframeHeight = Math.min(
iframe.contentWindow.window.document.documentElement.scrollHeight,
iframe.contentWindow.window.document.body.scrollHeight
);
$(iframe).height(iframeHeight);
}
這裡取 documentElement.scrollHeight 與 body.scrollHeight 兩者中的較小值,是為了避開各瀏覽器對 scrollHeight 解讀上的不一致:有的會回報實際內容高度,有的會回報視窗高度,取 min 通常能得到較可靠的結果。
<li><a href="selfinfo.jsp" target="c-c-iframe" title="個人信息">個人信息</a></li>
<li><a href="modifypass.jsp" target="c-c-iframe" title="修改密碼">修改密碼</a></li>
<iframe src="init.jsp" id="c-c-iframe" name="c-c-iframe" width="500px;"
frameborder="0" scrolling="no" marginwidth="0" marginheight="0"></iframe>
<script type="text/javascript">
<!--
$(function(){
$("#c-c-iframe").load(function(){
$(this).height($(this).contents().find("#content").height() + 40);
});
});
-->
</script>
find("#content") 是找出 iframe 內容文件中 id 為 content 那個元素的高度(也可以改寫成 find("body")),再把它設給 iframe。加 40 是預留邊距的空間。類似的邏輯也能用來設定寬度。
實際使用後做了一點調整,避免內容過短時 iframe 高度被壓得太扁:
<script type="text/javascript">
<!--
$(function(){
$("#workArea").load(function(){
var height = $(this).contents().find("#box").height() + 40;
$(this).height( height < 400 ? 400 : height ); // 給一個 400px 的最小高度
});
});
-->
</script>
find("body") 不太可靠。使用過程中找到 body 的高度往往不準確,尤其內容AYER有 margin 或浮動元素時。改為直接指定內容容器(例如 #content、#box)會穩定得多。
跨域會失敗。$(this).contents() 受同源政策限制,若 iframe 載入的是不同網域,瀏覽器會直接丟出安全性錯誤。這種情況下只能改用 postMessage 讓子頁主动回報高度給父頁。
另外補充一點作者的使用心得:製作無刷新的頁面切換時,iframe 有其優勢——天然相容瀏覽器的上一頁/下一頁按鈕;載入 Flash 也很乾脆,不必寫 object 標籤或一堆 JS 對接,還符合 W3C 標準。當然,在現代前端開發中,這些需求多半已由前端路由與 AJAX 取代,但 iframe 在嵌入第三方內容、報表預覽等場景仍有一席之地。