iframe 的常見需求主要有兩種:一是做出帶滾動條的區塊以節省版面;二是嵌入一個頁面,實現框架式連結。
如果不方便使用 iframe,其實有兩條替代路線:一是改用 CSS 排版,既少一個頁面請求,也能提高執行效率;二是用 xmlhttp 遠端取資料。
用層當容器:
#content { overflow: auto; height: 185px; width: 600px; background: #ccc; padding: 10px; }
示範:https://www.rexsong.com/blog/attachments/200601/02_150246_cssiframe1.htm
用 body 當容器:
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; }
示範:https://www.rexsong.com/blog/attachments/200601/02_151517_cssiframe2.htm
滾動條在外側:
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%; background: #ccc; height: 50px; z-index: 2; }
示範:https://www.rexsong.com/blog/attachments/200601/02_151837_cssiframe3.htm
滾動條在內側:
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; }
示範:https://www.rexsong.com/blog/attachments/200601/02_153241_cssiframe4.htm
在標準模式下,要把 body 看成一個容器,它的行為基本和 div 類似——這和傳統思維很不一樣。搞清楚了 html 與 body 的關係,很多進階排版問題自然迎刃而解。