:hover 偽類(現代標準,IE6 不支援非 a 元素)#div:hover { background: #000; }
測試:IE6.0、Firefox 2.0、Opera 9.23 均失效(IE6 僅支援 a:hover)。
<div onmouseover="this.style.backgroundColor='#F4F9FD'"
onmouseout="this.style.backgroundColor='#FFFFFF'">
內容
</div>
優點:零 CSS 依賴、極度相容。缺點:行為混入結構、難維護、CSP 限制。
<style>
.d_out { background-color: #EFEFEF; }
.d_over { background-color: #307172; }
</style>
<div class="d_out"
onmouseover="this.className='d_over'"
onmouseout="this.className='d_out'">
內容
</div>
優點:樣式集中管理、JS 僅切換類別、相容性極佳。缺點:仍需行內事件。
a {
display: block; width: 100px; height: 22px; line-height: 22px;
color: red; text-decoration: none;
}
a:hover { background: #f4f4f4; color: #000; }
<a> 天生支援 :hover(含 IE6),配合 display:block 即成區塊按鈕。但會影響頁面所有連結,需限定範圍(.nav a:hover)。
.hover-bg {
background: #fff;
transition: background 0.2s;
}
.hover-bg:hover { background: #f4f9fd; }
現代瀏覽器(IE9+)全支援任意元素 :hover,無需 JS。專案若已棄用 IE8,請直接使用此方案。