點擊網頁上的連結後,游標停留處會浮現一圈醜陋的虛線外框。這在講究細節的介面設計裡顯得格外突兀,因此常有設計主管要求前端「想辦法把它拿掉」。本文整理一套同時覆蓋 IE6、IE7 與 Firefox 的做法。
連結被點擊後會取得鍵盤焦點,瀏覽器便為它畫上虛線框以示「目前焦點在此」。IE 系列與 Firefox 對焦點的處理方式不同,所以需要分別對待:IE 靠私有行為(behavior)組件,Firefox 則用標準的 outline 屬性。
把下面的程式碼存成 link.htc:
<public:attach event="onfocus" onevent="hscfsy()" />
<script language="javascript">
function hscfsy(){
this.blur();
}
</script>
原理很直白:一旦元素取得焦點,就立刻把焦點移開,虛線框自然不會留下。
<a href="#" title="連結範例">示例連結</a>
用 CSS 把行內連結轉成有寬有高的方塊,文字水平與垂直都居中:
a {
display: block;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
}
a:hover {
background: #ddd;
}
只要多加一行 behavior,IE 的虛線框就消失了:
a {
display: block;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
overflow: hidden;
behavior: url(line.htc);
}
此時 IE6、IE7 已無問題,Firefox 卻仍在畫那圈虛線。Firefox 用的是 outline,因此再補一條規則:
a:focus { outline: 0; }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>去除連結虛線框</title>
<style type="text/css">
a {
display: block;
width: 100px;
height: 30px;
line-height: 30px;
text-align: center;
overflow: hidden;
behavior: url(line.htc);
}
a:hover { background: #ddd; }
a:focus { outline: 0; }
</style>
</head>
<body>
<a href="#" title="連結範例">示例連結</a>
</body>
</html>
移除焦點框會讓鍵盤使用者失去「目前在哪裡」的視覺線索,對無障礙體驗有負面影響。若網站需要兼顧可近性,較妥當的做法是保留虛線,或改用 a:focus 自訂一組更清楚、對比更足夠的焦點樣式,而不是直接歸零。