iframe 常見的用途有兩個:一是做出帶捲軸的區塊以節省版面,二是嵌入外部頁面形成框架連結。
但如果不方便使用 iframe,其實有替代途徑:用 CSS 排版直接做出同等效果(還能少一個請求、效能更好),或用 XMLHttpRequest 遠端取資料後填入頁面。以下整理幾種以 CSS 模擬 iframe 卷動區的寫法。
#content {
overflow: auto;
height: 185px;
width: 600px;
background: #ccc;
padding: 10px;
}
最單純的一種:固定寬高加上 overflow:auto,內容超出就出現捲軸。
html { overflow: hidden; height: 100%; background: #fff; border: 0; }
* html { padding: 200px 0 0 100px; }
body {
overflow: auto;
background: #ccc;
margin: 0;
position: absolute;
top: 200px; left: 100px; bottom: 0; right: 0;
}
* html body { height: 100%; width: 100%; position: static; }
把 body 本身當成一個可捲動的容器,用絕對定位的四邊把它釘在視窗的指定範圍內。帶星號的 hack 是給 IE 的補償寫法。
html { overflow: hidden; border: 0; height: 100%; }
body { overflow: hidden; margin: 0; height: 100%; position: relative; }
#content { height: 100%; position: relative; z-index: 1; overflow: auto; }
#head {
position: absolute; top: 0; right: 16px;
width: 100%; height: 100px; background: #ccc; z-index: 2;
}
#foot {
position: absolute; bottom: 0; right: 16px;
width: 100%; height: 50px; background: #ccc; z-index: 2;
}
內容區佔滿全高並自行捲動,頭尾用絕對定位疊在上層(z-index 較高),right 留出 16px 剛好讓開瀏覽器捲軸的位置。
html { height: 100%; max-height: 100%; border: 0; overflow: hidden; }
* html { padding: 100px 0 50px 0; }
body { height: 100%; max-height: 100%; margin: 0; overflow: hidden; }
#content {
position: absolute;
top: 100px; bottom: 50px; left: 0; right: 0;
z-index: 3; width: 100%; overflow: auto;
}
* html #content { top: 100px; bottom: 0; height: 100%; }
#head {
position: absolute; margin: 0; top: 0; left: 0;
width: 100%; height: 100px; background: #ccc; z-index: 5;
}
#foot {
position: absolute; margin: 0; bottom: 0; left: 0;
width: 100%; height: 50px; z-index: 5; background: #ccc;
}
這版的差別是捲軸只出現在中間的內容區,頭尾固定不動,視覺上更接近「整頁只有一塊在捲」的效果。
在標準模式下,body 基本上就是一個和 div 類似的方塊容器,這和傳統「body 只是頁面外殼」的直覺很不一樣。一旦把 html 與 body 的關係想通——html 是視窗的替身、body 是頁面最外層的容器——許多關於全高版面、固定頭尾的進階配置問題都會自然迎刃而解。
相較於 iframe,這些做法的好處是內容與主文件同屬一份 DOM,樣式、字型、腳本操作都連貫;代價則是無法真正嵌入跨網域的獨立頁面,那種情境仍得回到 iframe 或改用 API 取資料。