DIV CSS 佈局教程網

jQuery 點擊自動高亮:原理與實作程式碼
編輯:JavaScript綜合知識     

點擊某個項目時讓它短暫高亮再回復原狀,是很常見的視覺回饋。原理不複雜:幫元素掛上一個自訂屬性,用屬性選擇器對應到一段樣式,幾百毫秒後再把屬性移除。

第一步:擴充一個 hoverEl 方法

$.extend($.fn, {
 hoverEl: function(){
 var _this = $(this);
 var _t = setTimeout(function(){
 _this.attr("hover", "on");
 }, 10);
 _this.attr("hoverTimeout", _t);
 setTimeout(function(){
 clearTimeout( _this.attr("hoverTimeout") );
 var _t = setTimeout(function(){
 _this.removeAttr("hover");
 }, 100);
 _this.attr("hoverTimeout", _t);
 }, 200);
 }
});

流程是:10 毫秒後掛上 hover="on",200 毫秒後清掉計時器,再等 100 毫秒把屬性移掉。用屬性存計時器 id 是為了避免連續點擊時多組計時器互相干擾。

第二步:用屬性選擇器定義樣式

li[hover=on]{
 background-image: -webkit-linear-gradient(top, #4286F5, #194FDB) !important;
 color: white !important;
 cursor: pointer !important;
}

只要 hover 屬性存在,這段樣式就會自動套用;屬性一移除,外觀立刻復原。

呼叫方式

$(e.target).hoverEl();

這個技巧的優點是完全不碰元素的 class,因此不會覆蓋掉既有的樣式類別。若想更簡潔,也可以改用 addClass 搭配 CSS transition,把動畫交給瀏覽器處理,效能與流暢度通常更好。

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