鏈接(<a>)獲得焦點時,瀏覽器預設繪製虛線框(focus outline),提示鍵盤用戶當前焦點位置。視覺設計上常需隱藏,但不可直接移除無障礙功能。
<a href="#" hidefocus="true">無虛線框</a>
/* 等價於 */
<a href="#" onfocus="this.blur()">無虛線框</a>
hidefocus 或 hidefocus="true" 均可。a { outline: none; }
直接移除 outline 會嚴重損害鍵盤導航無障礙性(WCAG 2.4.7)。正確做法是提供清晰的自定義焦點樣式:
a:focus {
outline: none; /* 移除預設虛線 */
box-shadow: 0 0 0 2px #0066cc; /* 自定義高對比度焦點環 */
border-radius: 2px;
}
/* 僅在鍵盤導航時顯示(現代瀏覽器) */
a:focus:not(:focus-visible) { outline: none; box-shadow: none; }
a:focus-visible {
outline: none;
box-shadow: 0 0 0 2px #0066cc;
}
/* 1. 移除預設 outline */
a { outline: none; }
/* 2. IE6/7 專用 hidefocus(可選,條件註釋引入) */
<!--[if lte IE 7]>
<style> a { behavior: expression(this.hideFocus=true); } </style>
<![endif]-->
/* 3. 提供統一焦點樣式 */
a:focus,
a:active { /* IE7/8 :active 兼容 */
box-shadow: 0 0 0 2px #0066cc;
border-radius: 2px;
}
| 方案 | 支援範圍 | 標準性 | 無障礙 |
|---|---|---|---|
| hidefocus | IE only | 非標準 | 破壞 |
| outline: none | 全瀏覽器 | 標準 | 破壞(若無替代) |
| outline: none + :focus-visible 自定義樣式 | 現代瀏覽器 | 標準 | ✅ 完美支援 |
建議:現代專案直接使用 outline: none 配合 :focus-visible 自定義焦點樣式;需支援 IE11 時添加 :focus 降級。堅決避免使用 hidefocus 或 onfocus="this.blur()"。