jQuery Tools 的 Tooltip 是一款靈活的提示框組件,能為表單欄位、按鈕等元素加上精美的浮動提示。本文透過完整範例,系統性地介紹它的用法、屬性、事件與腳本 API。
<!DOCTYPE html>
<html>
<head>
<title>jQuery Tools standalone demo</title>
<script src="https://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js"></script>
<link rel="stylesheet" type="text/css" href="./tooltip-generic.css"/>
<style>
#myform {
border:1px outset #ccc;
background:#fff repeat-x;
padding:20px;
margin:20px auto;
width:350px;
font-size:12px;
-moz-border-radius:4px;
}
#myform h3 {
text-align:center;
margin:0 0 10px 0;
}
#inputs label, #inputs input, #inputs textarea, #inputs select {
display: block;
width: 150px;
float: left;
margin-bottom: 20px;
}
#inputs label {
text-align: right;
width: 75px;
padding-right: 20px;
}
#inputs br {
clear: left;
}
</style>
</head>
<body><form id="myform" action="#">
<h3>Registration Form</h3>
<div id="inputs">
<label for="username">Username</label>
<input id="username" title="Must be at least 8 characters."/>
<br />
<label for="password">Password</label>
<input id="password" type="password" title="Make it hard to guess." />
<br />
<label for="email">Email</label>
<input id="email" title="We won't send you any marketing material." />
<br />
<label for="body">Message</label>
<textarea id="body" title="What's on your mind?"></textarea>
<br />
</div>
<button type="button" title="This button won't do anything">Proceed</button>
</form>
<script>
$(function() {
$("#myform :input").tooltip({
position: "center right",
offset: [-2, 10],
effect: "fade",
opacity: 0.7
});
});
</script>
</body>
</html>
/* simple css-based tooltip */
.tooltip {
background-color:#000;
border:1px solid #fff;
padding:10px 15px;
width:200px;
display:none;
color:#fff;
text-align:left;
font-size:12px;
-moz-box-shadow:0 0 10px #000;
-webkit-box-shadow:0 0 10px #000;
}
CSS 並非必要,但若不設定,提示框的外觀會相對樸素。
$("#myform :input").tooltip({
position: "center right",
offset: [-2, 10],
effect: "fade",
tipClass:'tooltip', // 預設值:tooltip
opacity: 0.7
});
最簡單的初始化寫法為 $("#myform :input").tooltip();。
以下範例在提示框顯示時,讓觸發元素緩慢淡變至 0.8 透明度:
$("label").tooltip({
onShow: function() {
this.getTrigger().fadeTo("slow", 0.8);
}
});
jQuery 提示框讓你能完全掌控顯示與隱藏的時機,並可為不同元素類型指定不同事件,其預設值如下:
events: {
def: "mouseenter,mouseleave", // 元素的預設顯示/隱藏事件
input: "focus,blur", // 所有 input 元素
widget: "focus mouseenter,blur mouseleave", // select、checkbox、radio、button
tooltip: "mouseenter,mouseleave" // 提示框元素
}
內建的「淡入淡出」效果有專屬的組態選項:
掌握以上屬性、事件與 API,便能靈活打造各式精美的提示框互動效果。