DIV CSS 佈局教程網

純 JS 實作表格儲存格懸停提示:延遲顯示完整內容的氣泡方案
編輯:關於JavaScript     

表格裡有些欄位文字太長,於是先用文字溢出的方式處理,但這麼一来使用者就看不到完整內容了。目標很明確:滑鼠移上去時,把被隱藏的文字完整顯示出來。

網路上現的外掛不少,我沒採用,而是自己寫了一個:停留約一秒後在游標位置顯示氣泡層,移開立即隱藏。

CSS 部分

 <style> #showbox { width: 150px; min-height: 50px; font: 100 14px/1 "微軟雅黑"; border: 1px solid #3c8dbc; display: none; position: absolute; top: 0; left: 0; background-color: #fff; padding: 5px; } </style>

HTML 部分

 <table id="example1" role="grid"> <thead style="background-color: #E4E9F0;"> <tr role="row"> <th rowspan="2" style="text-align: center; width: 6%;" class="sorting_disabled " colspan="1"><font style="font-weight:bold;">序號</font></th> <th rowspan="2" style="text-align: center; width: 10%;" class="sorting_disabled " colspan="1"><font style="font-weight:bold;">名稱</font></th> <th rowspan="2" style="text-align: center; width: 10%;" class="sorting_disabled " colspan="1"><font style="font-weight:bold;">類別</font></th> <th rowspan="2" style="text-align: center; width: 8%;" class="sorting_disabled" colspan="1"><font style="font-weight:bold;">單位</font></th> <th rowspan="2" style="text-align: center; width: 26%;" class="sorting_disabled " colspan="1"><font style="font-weight:bold;">成果要求</font></th> <th colspan="2" style="text-align: center; " rowspan="1"><font style="font-weight:bold;">進展</font></th></tr> <tr role="row"> <th style="text-align: center; width: 30%;" class="sorting_disabled" rowspan="1" colspan="1"><font style="font-weight:bold;">最新進展</font></th> <th style="text-align: center; width: 10%;" class="sorting_disabled " rowspan="1" colspan="1"><font style="font-weight:bold;">更新時間</font></th></tr> </thead> <tbody> <tr role="row"> <td>1</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td></td> </tr> <tr role="row"> <td>2</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td></td> </tr> <tr role="row" class="odd"> <td>3</td> <td>阿拉蕾</td> <td>阿拉蕾</td> <td>阿拉蕾,</td> <td>阿拉蕾</td> <td></td> </tr> </tbody> </table> <div id="showbox"></div>

JS 部分

 $(function() { function showBox(obj,box){ var timer = null; $(obj).on("mouseover", function (e) { clearTimeout(timer); var clientX = e.clientX; var clientY = e.clientY; var txt = $(this).text(); timer = setTimeout(function () { $(box).css("left", clientX).css("top", clientY); if (txt == "") { $(box).hide(); } else { $(box).show(); $(box).html(txt); } }, 1000); }); $(obj).on("mouseout",function(){ clearTimeout(timer); $(box).hide(); }); } showBox("#example1 > tbody td","#showbox"); });

程式碼刻意抽成 showBox(obj, box) 的通用形式,只要傳入不同的選擇器就能套用到其他表格上,不必複製貼上。

最後補一個更省事的方向:Bootstrap 內建的 tooltip 元件本來就能勝任這件事。一開始我不熟所以沒用,後來經人提醒才發現,直接給元素的 title 屬性賦值為儲存格的文字即可,寫法比自己維護氣泡層簡單不少,只是樣式客製空間相對受限。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved