瀏覽器原生的 title 提示外觀無法客製、出現時機也不可控。用少少一點 jQuery 加上 CSS,就能做出外觀統一、位置精準的自製提示框。

$(function () {
$("a[title]").each(function () {
var a = $(this);
var title = a.attr('title');
if (title == undefined || title == "") return;
a.data('title', title) // 先把文字存起來
.removeAttr('title') // 移除原生 title,避免雙重提示
.hover(
function () {
var offset = a.offset();
$('<div id="anchortitlecontainer"></div>')
.appendTo($("body"))
.html(title)
.css({
top: offset.top + a.outerHeight() + 10,
left: offset.left + a.outerWidth() + 1
})
.fadeIn(function () {
var pop = $(this);
setTimeout(function () {
pop.remove();
}, pop.text().length * 80); // 依字數決定顯示時間
});
},
function () {
$("#anchortitlecontainer").remove();
}
);
});
});
別忘了先引入 jQuery。這段程式碼有兩個細節值得學:
一是 setTimeout(..., pop.text().length * 80)——依文字長度動態計算顯示時間,避免「短文字提示拖太久」或「長文字還沒讀完就消失」。
二是把 title 存進 jQuery 的 data 快取後才 removeAttr,這樣既擺脫了原生提示,又保留了原始內容。
#anchortitlecontainer {
position: absolute;
z-index: 5999;
border: solid 1px #315B6C;
padding: 5px;
color: #315B6C;
background: none repeat scroll 0 0 #FFFFFF;
border-radius: 5px;
display: none;
}
#anchortitlecontainer:before {
position: absolute;
bottom: auto;
left: -1px;
top: -15px;
border-color: transparent transparent transparent #315B6C;
border-style: solid;
border-width: 15px;
content: "";
display: block;
width: 0;
}
#anchortitlecontainer:after {
position: absolute;
bottom: auto;
left: 0px;
top: -13px;
border-color: transparent transparent transparent #FFFFFF;
border-style: solid;
border-width: 15px;
content: "";
display: block;
width: 0;
}
那個指向連結的小三角形,是用兩個偽元素疊出來的::before 畫較大的深色三角當外框,:after 畫較小的白色三角蓋在內層,兩者位置差 1 到 2 像素,視覺上就形成了帶描邊的箭頭。這是完全不用圖片的純 CSS3 做法,解析度高、檔案小、顏色好改。
實務上還可以再補一點:為提示框加上 pointer-events:none,避免它擋住滑鼠造成 flicker;若頁面靠右側有連結,記得判斷邊界避免提示溢出畫面。