原生 title 屬性雖能顯示提示,但樣式無法控制、出現延遲長、無法附加圖示。以下示範如何自製。
<!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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>原生提示</title>
</head>
<body>
<a href="https://www.softwhy.com" title="螞蟻部落">螞蟻部落</a>
</body>
</html>
能用,但外觀由作業系統決定,無法與設計稿對齊。
核心思路是把提示文字放進一個預設隱藏的 <span>,滑鼠移入連結時讓它顯示,並以絕對定位把它挪到旁邊。
<!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">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
<title>自訂連結提示</title>
<style type="text/css">
ul {
list-style: none;
font-size: 14px;
}
li {
width: 100px;
height: 30px;
line-height: 30px;
float: left;
text-align: center;
position: relative;
border: 1px solid red;
}
span { display: none; }
a:link, a:visited { text-decoration: none; }
a:hover .tishi {
display: block;
width: 100px;
height: 30px;
background-color: #6C9;
line-height: 30px;
text-align: center;
position: absolute;
left: 80px;
top: 40px;
color: #FFFFFF;
}
</style>
</head>
<body>
<ul>
<li><a href="#" class="mylink">DIV+CSS<span class="tishi">DIV+CSS</span></a></li>
<li><a href="#" class="mylink">jQuery<span class="tishi">jQuery</span></a></li>
<li><a href="#" class="mylink">JS<span class="tishi">JS</span></a></li>
<li><a href="#" class="mylink">HTML<span class="tishi">HTML</span></a></li>
<div style="clear:both"></div>
</ul>
</body>
</html>
li 必須設 position: relative。否則提示框的 position: absolute 會以整個文件為基準,left/top 的數值就完全亂掉。
提示框的 left 與 top 是相對於 li 計算的。本例中 80px / 40px 讓它落在連結右下方。
用 a:hover .tishi 而非 li:hover,可確保只有滑鼠真正在連結上時才顯示。
寫法可以更簡潔,也更好維護:
.mylink {
position: relative;
}
.mylink .tishi {
position: absolute;
left: 100%;
top: 100%;
margin: 8px 0 0 8px;
padding: 6px 10px;
background: #6C9;
color: #fff;
white-space: nowrap;
opacity: 0;
visibility: hidden;
transition: opacity .15s;
}
.mylink:hover .tishi,
.mylink:focus .tishi {
opacity: 1;
visibility: visible;
}
用 opacity + visibility 取代 display: none,可以做淡入動畫,也不會觸發回流。同時加上 :focus,鍵盤使用者也能看到提示。
若提示內容並非裝飾性資訊,請考慮改用 aria-describedby 讓輔助技術能讀取;純視覺的提示則應加上 aria-hidden="true",避免被重複朗讀。