需求是這樣的:表格裡有些欄位文字過長,於是用了文字溢出的方式處理,但這麼一來就看不到完整內容了。希望滑鼠移上去時,能把被隱藏的文字完整顯示出來。
網路上這類外掛很多,但我沒用,自己寫了一個:延遲一秒後在游標位置彈出一個氣泡層,移開立即隱藏。
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"); });
兩個設計決定值得說明:一是加上 1 秒延遲(搭配 mouseout 時的 clearTimeout),滑過而不停留時不會亂彈,這是體驗上很關鍵的一手;二是空字串時直接隱藏氣泡,避免出現空白框。
最後補充一個更省事的做法:Bootstrap 本身就有 tooltip 元件,雖然官方範例多用 title 屬性,但實務上直接給 title 賦值為儲存格的 text 即可。一開始我不會用這個方式,後來被人點醒才發現,確實比自己寫氣泡層簡潔許多。