選項卡(Tab)是網頁常見元件。本文示範如何封裝一個可複用的 jQuery 選項卡插件,並巧妙地加入「滑鼠延遲」機制,避免滑鼠不小心掠過時就急著切換,提升操作體驗。
.tab{width: 350px;margin: 100px auto;}
.tabnav li{ list-style:none;cursor:pointer;float: left;width: 80px;border: 1px solid #ccc;border-radius: 5px;margin-right: 5px; height:24px;line-height: 24px;text-align: center;}
.tabnav li.cur{background:#daa520;}
.tabcontent{display: none;padding: 20px;}
.tabcon{border: 1px #708090 solid;background: #ffc0cb;height: 300px;clear: both;}
透過 $.fn.extend 擴充 myTab 方法,重點是每個導航項綁定事件後,用 setTimeout 延遲 300 毫秒才切換,並在 mouseout 時清除計時器:
(function($){
$.fn.extend({
myTab: function(options){
var confings = {
tabNav: '', // tab 導航名稱
tabTag: '', // tab 導航標簽
tabCon: '', // tab 內容名稱
conTag: '', // tab 內容標簽和類名
method: 'click' // 滑鼠事件狀態
};
options = $.extend(confings, options);
var tabLi = $(confings.tabNav).find(confings.tabTag);
var tabcon = $(confings.tabCon);
var tabUl = tabcon.find(confings.conTag);
var timoutid = null;
tabLi.each(function(ind){
$(this).bind(options.method, function(){
var liNode = $(this);
timoutid = setTimeout(function(){ // 滑鼠不小心劃過的延遲時間
tabUl.hide();
tabLi.removeClass("cur");
tabUl.eq(ind).show();
liNode.addClass("cur");
}, 300);
}).mouseout(function(){
clearTimeout(timoutid);
});
});
return this;
}
});
})(jQuery);
可以同時初始化多組選項卡,並透過參數指定滑鼠事件類型:
$(function(){
$("#testtab5").myTab({
tabNav: "#tabtag5", tabTag: "li", tabCon: "#tabcon5", conTag: ".tabcontent", method: "mouseover"
});
$("#testtab").myTab({
tabNav: "#tabtag", tabTag: "li", tabCon: "#tabcon", conTag: ".tabcontent"
});
});
HTML 結構由導航列表 .tabnav 與內容區 .tabcon 組成,每個內容區塊對應一個 .tabcontent。這個延遲切換的小巧思,能大幅減少使用者滑過時的誤觸。