為元素加上 title 屬性後,滑鼠移上去瀏覽器會顯示一個預設的提示框。這些提示框樣式千篇一律、無法自訂,而透過 jQuery UI 的 tooltip() 函數,就能輕鬆做出不一樣的外觀。
只需要一行 $(document).tooltip();,即可將頁面上所有帶 title 的元素轉換為美化的懸浮提示框。以下是完整範例,存成 html 檔開啟即可看到效果。
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用 jQuery UI 修飾 title 屬性的氣泡懸浮框</title>
<script type="text/javascript" src="https://www.keleyi.com/keleyi/pmedia/jquery-1.9.1.min.js"></script>
<link rel="stylesheet" href="https://www.keleyi.com/keleyi/pmedia/jquery/ui/1.10.2/themes/sunny/jquery-ui.min.css" />
<script type="text/javascript" src="https://www.keleyi.com/keleyi/pmedia/jquery/ui/jquery-ui-1.10.2.custom.min.js"></script>
<script type="text/javascript">
$(function () {
$(document).tooltip();
});
</script>
<style type="text/css">
label { display: inline-block; }
</style>
</head>
<body>
<h2>不一樣的懸浮提示框</h2>
<p>如果為一個元素添加了 title 屬性,那麼當光標移到該元素上時,會在元素旁顯示出一個懸浮提示框。</p>
<p>一般懸浮提示框是無法使用樣式修飾的,但使用 jQuery UI,則可以顯示不同效果,方法很簡單:$(document).tooltip();</p>
<p><label for="age">Email:</label><input id="age" title="可作為取回密碼的手段,建議填寫。" /></p>
<p><a href="https://www.keleyi.com" target="_blank" title="柯樂義首頁">柯樂義</a></p>
</body>
</html>
把滑鼠移到輸入框或超連結上,即可看到美化後的提示框效果。透過替換不同的 jQuery UI 主題 CSS,還能輕鬆換上多種外觀風格。