想為頁面上的關鍵字加上滑鼠移入即出現的說明框,不必自己刻,用 jQuery 的 Cluetip 插件就能搞定。它的官方範例頁在 plugins.learningjquery.com/cluetip/demo/,可以從那裡下載。
第一步當然是引入 jQuery 本體與 Cluetip 的 JS 檔,接著只要兩個步驟就能運作:
<a class="title" href="#" title="This is the title|The first set of contents comes after the first delimiter.....">
$('a.title').cluetip({splitTitle: '|'});
當連結被點擊時,會彈出一個提示框:標題顯示 This is the title,內容則是竖線後方那段文字。splitTitle 就是告訴插件用哪個字元切分標題與本文,這樣便能在一個 title 屬性裡同時放兩種資訊。
若希望彈出框載入另一個頁面的內容,用 rel 屬性指定來源即可:
<a class="basic" href="ajax.htm" rel="ajax.htm">
$('a.basic').cluetip();
<a class="custom-width" href="ajax3.htm" rel="ajax3.htm">
$('a.custom-width').cluetip({width: '200px', showTitle: false});
showTitle: false 可以把標題列整個拿掉,適合只想要一塊純內容的提示框。
預設行為是點擊觸發,若要改成 hover,得指定用哪個屬性當作內容來源:
<h4 title="Fancy Title!" id="ajax3.htm">Hover over me</h4>
$('h4').cluetip({attribute: 'id', hoverClass: 'highlight'});
這裡用 attribute: 'id' 把 id 當成內容網址,並用 hoverClass 在滑鼠移入時為元素加上高亮樣式,給使用者一個「這裡可以互動」的視覺暗示。
<a href="ajaxclick.htm" rel="ajax5.htm" title="active ingredients" id="clickme">
$('#clickme').cluetip({activation: 'click', width: 650});
把 activation 設為 click,就回到點擊觸發,同時指定 650px 的寬度容納較長的內容。
<a href="ajax4.htm" title="|first line body|second line body">
$('ol.rounded a:eq(0)').cluetip({splitTitle: '|', dropShadow: false, cluetipClass: 'rounded', showTitle: false});
cluetipClass 是套用自訂樣式類別的入口,把它設為 rounded 並在 CSS 中定義圓角,就能得到圓角提示框;同時關掉 dropShadow 讓視覺更乾淨。這裡也用 :eq(0) 精準指定只作用在第一個符合的連結上,示範了如何避免效果外溢到其他元素。