復制代碼 代碼如下:
<iframe onload="Javascript:SetIFrameHeight(this)" src="../Home/b" id="win" name="win" width="100%" height="1"> </iframe>
<script type="text/javascript">
function SetIFrameHeight(obj) {
var win = obj;
if (document.getElementById) {
if (win && !window.opera) {
if (win.contentDocument && win.contentDocument.body.offsetHeight)
win.height = win.contentDocument.body.offsetHeight;
else if (win.Document && win.Document.body.scrollHeight)
win.height = win.Document.body.scrollHeight;
}
}
}
</script>
思路很簡單:利用 iframe 加載完畢時的 onload 事件,讀取被嵌套網頁的高度,再賦值給 iframe 自身的高度即可。代碼中對標準瀏覽器(contentDocument)與 IE(Document)做了兼容判斷。
當主頁面與被嵌套的 iframe 屬於不同域名時,就稍微麻煩一些,需要繞開 JavaScript 的跨域限制。原理是借助一個與主頁同域的中介頁面來傳遞高度:現有 iframe 主頁面 main.html、被嵌套頁面 iframe.html、中介頁面 agent.html 三個,通過 iframe.html 把自身高度寫入一個同域中介頁 agent.html 的地址,agent.html 取得高度後再設置 main.html 中 iframe 的高度。
iframe 主頁面 main.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head><title>iframe主頁面</title></head>
<body>
<div style="border:1px solid #ccc;padding:10px;">
<iframe id="frame_content" name="frame_content" src="iframe.html" width="100%" height="0" scrolling="no" frameborder="0"></iframe>
</div>
<br />尾部<br />
</body>
</html>
iframe 嵌套頁面 iframe.html:
復制代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head><title>被iframe嵌套頁面</title></head>
<body>
文字<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
文字<br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<iframe id="iframeC" name="iframeC" src="" width="0" height="0" style="display:none;" ></iframe>
<script type="text/javascript">
function sethash(){
hashH = document.documentElement.scrollHeight;
urlC = "agent.html";
document.getElementById("iframeC").src=urlC+"#"+hashH;
}
window.onload=sethash;
</script>
</body>
</html>
iframe 中介頁面 agent.html:
復制代碼 代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head><title>iframe中介頁面</title></head>
<body>
<script>
function pseth() {
var iObj = parent.parent.document.getElementById('frame_content');
iObjH = parent.parent.frames["frame_content"].frames["iframeC"].location.hash;
iObj.style.height = iObjH.split("#")[1]+"px";
}
pseth();
</script>
</body>
</html>
需要特別說明的是:main.html 與 agent.html 必須處於同一個域,而被嵌套的 iframe.html 位於另一個域。正是利用「中介頁與主頁同域」這一點,通過 URL 的 hash 值作為傳參載體,巧妙地迴避了跨域限制,最終實現了跨域 iframe 的高度自適應。