在 JSP 頁面嵌入 <iframe> 載入跨域或同域子頁面時,常需讓 iframe 高度隨內容自動調整,避免雙滾動條或內容截斷。傳統做法利用 location.hash 傳遞高度數值,配合父頁面輪詢或 onload 事件實現。
<body>
<!-- 隱藏的代理 iframe,用於接收子頁面傳回的高度 -->
<iframe id="agentFrame" name="agentFrame" src="" width="0" height="0" style="display:none;"></iframe>
<!-- 實際顯示內容的 iframe -->
<iframe id="infoFrame" name="infoFrame" src="/child.jsp" width="100%" height="500" frameborder="0"></iframe>
<script type="text/javascript">
function setHash() {
// 取得文檔完整高度
var hashH = document.documentElement.scrollHeight;
// 設定代理 iframe src,將高度放入 hash 片段
var urlC = "/test.jsp"; // 代理頁面,同域才能通訊
document.getElementById("agentFrame").src = urlC + "#" + hashH;
}
window.onload = setHash;
</script>
</body>
<%@ page contentType="text/html;charset=GBK" language="java"%>
<script>
function pseth() {
// 取得父頁面的 infoFrame 元素
var iObj = parent.parent.document.getElementById('infoFrame');
// 從 agentFrame 的 location.hash 取得高度值
var iObjH = parent.parent.frames["infoFrame"].frames["agentFrame"].location.hash;
// 格式為 "#數值",split 取後段並加 px
iObj.style.height = iObjH.split("#")[1] + "px";
}
window.onload = pseth;
</script>
parent.parent.document 或 frames[]。window.onload 確保圖片、CSS 皆載入完畢,scrollHeight 才準確。postMessage API(支援跨域)或 ResizeObserver 監聽內容變化,寫法更簡潔安全。若子頁面同域,可在子頁面 onload 直接執行:
// child.jsp
window.onload = function() {
parent.document.getElementById('infoFrame').style.height =
document.documentElement.scrollHeight + 'px';
};
此法無需隱藏 iframe 與代理頁面,維護成本較低。