先看一個常見的錯誤示範:
<a href=""><div><span>合乎</span></div></a>
這種寫法並不合規範。把 div、span 塞進 a 的偽類裡,語意與結構上都不恰當。若只是想做出滑鼠移入變色的效果,用 onmouseover 與 onmouseout 事件來控制反而更乾脆。
<style>
body,td{font-family:Verdana,Arial,宋體; font-size:9pt;}
a{color:#000000;text-decoration:none;}
a:visited{color:#000000;text-decoration:none;}
a:hover{color:#000000;text-decoration:none;}
.classCSS{letter-spacing:7;}
.tex{border:#000000 1px solid; font-family:"Verdana,Arial,宋體"; font-size:9pt; height:20px}
</style>
<script language="JavaScript">
function overtable(this_s){
this_s.style.background='#CFD6E8';
this_s.style.border='1pt solid #0a246a';
}
function downtable(this_s){
this_s.style.backgroundColor='#8592b5';
}
function outtable(this_s){
this_s.style.background='';
this_s.style.border='0pt solid #d4d0c8';
}
</script>
三個函數分別負責移入、按下、移出:移入時換底色並加上深色外框,按下時再加深一階,移出時全部還原。
<table width="279" border="0" cellspacing="0" cellpadding="0" align="center">
<tr align="center" valign="middle">
<td class="classCSS" height="24"
onMouseDown="downtable(this)"
onMouseOver="overtable(this)"
onMouseOut="outtable(this)"
style="cursor:hand">
<a href="https://www.e-cn-e.com/index.htm" onFocus="this.blur()" target="content">健康上網忠告:適度上網益腦,沉迷網絡傷身;合理安排時間,享受健康生活。</a>
</td>
</tr>
</table>
重點是把三個事件綁在 td 上,並用 this 把當前元素傳進函數。加上 cursor:hand 讓游標變成手型,而 onFocus="this.blur()" 則是為了避免點擊後出現虛線框。
如果目標區塊本身就是連結,其實用 CSS 的 a:hover 搭配 display:block 就能做到類似效果,程式碼更少、也更好維護——只有在需要更複雜的狀態切換時,才值得搬出 JavaScript。