本文彙整日常網頁製作中常見的 xHTML、CSS 與 JavaScript 技巧與相容性問題,分區塊整理,方便隨時查閱。
文字與圖片底對齊:
<li>記住密碼<img src="" align="bottom" style="margin-bottom:-4px"/></li>
文字與圖片居中對齊:
<li>記住密碼<img src="static/img/xyx.jpg" align="middle"/></li>
更改 IE「查看原始碼」的編輯器:開啟 regedit,找到 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\View Source Editor\Editor Name,把預設值改為你的編輯器路徑即可。
自動最大化視窗:在 body 之間加入:
<SCRIPT language="javascript">
setTimeout('top.moveTo(0,0)',5000);
setTimeout('top.resizeTo(screen.availWidth,screen.availHeight)',5000);
</script>
window.opener:它是用 window.open 打開的子視窗的父視窗,可用來存取或設定父視窗的值與方法。
刷新頁面:可用 history.go(0)、location.reload()、location=location、document.URL=location.href 等方法;自動刷新則用 <meta http-equiv="refresh" content="20"> 或 setTimeout 搭配 reload。
CSS hack 命名注意:用下劃線開頭的命名(如 _style)是一種 hack,會讓多數非 IE 瀏覽器忽略該樣式,因此不建議用「_」作為命名分隔符,這是驗證時會報錯的原因。
a 標籤外的 hover:IE6 及以下不支援非 a 元素的 :hover,可用具體 class 搭配背景變化來達到效果。
hasLayout:很多 IE6/7 問題可用設定 hasLayout 解決,最簡單的方式是加上 height 或 width(如 height:1%),也可用 zoom。
字元重複:確保浮動元素設定了 display:inline,並可用 margin-right:-3px。
樣式優先級:內聯樣式 > ID 選擇器 > 類/屬性/偽類 > 元素標籤/偽元素。
垂直居中:用 position:absolute 搭配 top:50%、left:50% 與負的 margin 達到居中。
li 內含 a 與 img 出現空白:可讓 li 浮動並將 img 設為塊級、把 ul 的 font-size 設為 0、設 img 的 vertical-align:bottom,或給 img 負的 margin-bottom。
連結 L-V-H-A 順序:被點擊過的連結樣式失效時,調整 CSS 為 Link-Visited-Hover-Active 的順序。
長字串換行:用 word-wrap:break-word 與 overflow:hidden。
父容器高度不自適應:清除子元素的浮動。
圖片下方間隙:把 img 設為 display:block,或將父容器 font-size 設為 0。
LI 內容過長省略:white-space:nowrap 搭配 text-overflow:ellipsis 與 overflow:hidden。
文字垂直居中:讓 line-height 等於容器高度。
IE 滾動條樣式:用 scrollbar-face-color 等一系列專屬屬性設定。
讓層顯示在 Flash 之上:給 Flash 設 wmode 為 transparent 或 opaque。
加入收藏夾:用能力偵測分別處理 IE(window.external.AddFavorite)與 Firefox(window.sidebar.addPanel)等環境。
新聞列表:以 ul 搭配 li,內含 span(日期)與 a(標題)即可。
border:none 與 border:0:border:0 仍會渲染邊框寬度,border:none 則不渲染;在 IE6/7 的 button、input 上 border:none 可能無效,此時加背景屬性可讓它全相容。
多列等高:給每個需要等高的列套用 padding-bottom:32767px 與 margin-bottom:-32767px。
innerText / innerHTML / outerHTML:innerText 不含標籤,innerHTML 含內部標籤,outerHTML 含元素自身標籤。
數字轉換:Number() 遇到非數字字串回傳 NaN;parseInt() 從左到右盡量解析直到遇到非數字;parseFloat() 保留小數。
節點操作:nodeType(1 為元素節點、3 為文字節點)、nodeName、nodeValue、childNodes、firstChild、lastChild、parentNode 等。
可用 Math.pow 與 Math.round 實作指定小數位;用 Math.random 搭配 Math.floor 產生受約束的隨機數;用 String() 或 toString() 轉字串;用 arguments.length 取得傳入參數個數,用 function.length 取得定義的參數個數。
跨瀏覽器 inline-block:同時寫 -moz-inline-stack、inline-block、zoom:1 與 *display:inline。
清除浮動:用 clearfix:after 偽元素搭配 clear:both,並對 IE 用 zoom:1。
網址自訂圖示:製作 16×16 的 ico 檔並用 link 標籤引用,IE5 以上可直接放網站根目錄自動識別。
文字省略:div 設 width、height、overflow:hidden、text-overflow:ellipsis、white-space:nowrap。