DIV CSS 佈局教程網

讓 iframe 高度自適應內容的兩種做法
編輯:關於JavaScript     

使用 iframe 時,若內容高度不定,就會出現雙重捲軸或大片空白的困擾。要讓框架高度自動貼合內容,可以從父頁面或子頁面兩個方向著手。本文提供兩種做法。

做法一:由父頁面控制

這裡要理解框架的兩個屬性:contentWindow 與 contentDocument,它們的意思和 window、document 差不多。不同的是,contentWindow 所有瀏覽器都支援,而 contentDocument 在 IE6、IE7 以及舊版 Chrome 上並不支援。

 <iframe onload="change_height()"></iframe> function change_height(){ var iframe=document.getElementById("iframe_id"); //取得框架元素 var i_height=iframe.contentWindow.document.body.scrollHeight||iframe.contentWindow.document.documentElement.scrollHeight; //取得框架內容的高度 iframe.height=i_height; //改變 } 

做法二:由內容頁控制

在子頁面中,透過 parent 取得父頁面的框架元素,再依自身內容高度設定框架高度:

 window.onload=function(){ var iframe=parent.document.getElementById("iframe_id"); //取得框架元素 iframe.height=document.body.scrollHeight||document.documentElement.scrollHeight; //取得框架內容的高度並改變 } 

兩種做法的核心都是取得內容頁的 scrollHeight,再賦值給 iframe 的 height。你可以依實際架構選擇從父層或子層控制,都能達到高度自適應的效果。

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