iframe 高度自適應是個老問題,核心思路是:等 iframe 內容載入完成後,讀取內部文件的 scrollWidth 與 scrollHeight,再寫回 iframe 的寬高屬性。難點在於 IE 與其他瀏覽器的載入事件綁定方式不同。
var temp_iframe
var content = document.getElementById('right'); // 在 id 為 right 的容器中建立 iframe
var c = 0;
function append(filename)
{
var the_iframe = "helpfile" + c;
temp_iframe = document.createElement("iframe");
temp_iframe.src = filename;
temp_iframe.scrolling = "no";
temp_iframe.setAttribute("frameborder", "0");
temp_iframe.id = the_iframe;
temp_iframe.name = the_iframe;
scroll(0, 0);
content.innerHTML = "";
content.appendChild(temp_iframe);
if (document.all)
{
temp_iframe.attachEvent('onload', function()
{
temp_iframe.setAttribute("width", window.frames[the_iframe].document.body.scrollWidth);
temp_iframe.setAttribute("height", window.frames[the_iframe].document.body.scrollHeight);
});
}
else
{
temp_iframe.addEventListener('load', function()
{
temp_iframe.setAttribute("width", window.frames[the_iframe].document.body.scrollWidth);
temp_iframe.setAttribute("height", window.frames[the_iframe].document.body.scrollHeight);
}, false);
}
c++;
return false;
}
這份寫法在 IE6、IE7、IE8 與 Firefox 3.6 下都測試通過。呼叫方式有兩種,把腳本另存為 iframe.js 後:
<a href="index.html" onclick="return append('xxxx.html')" class="li1">
<div id="right"></div>
<script type="text/javascript" src="iframe.js"></script>
或者把函式最後的 return false 拿掉,改用:
<a href="javascript:append('favorite/Favorites.html')" class="li1">
<div id="right"></div>
<script type="text/javascript" src="iframe.js"></script>
還有兩個可以再打磨的地方:設定自適應寬高的那段邏輯其實可以抽成獨立函式重複呼叫;另外每次建立的 iframe 都得換不同的 id 與 name,即使先刪掉舊的也一樣麻煩,這部分還在摸索更好的處理方式。