萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實作按鈕點擊瞬間高亮再淡出效果

設計概念

點擊元素時,暫時加上自訂屬性 hover="on",搭配 CSS 屬性選擇器套用高亮樣式,延遲移除屬性還原外觀。

jQuery 外掛: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 t2 = setTimeout(function(){ $this.removeAttr('hover'); }, 100);
            $this.attr('hoverTimeout', t2);
        }, 200);
    }
});

CSS 樣式

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

使用範例

// 在 click 事件中呼叫
$(e.target).hoverEl();

優化建議

  • 改用 addClass('highlight') / removeClass('highlight'),語意更清晰、效能更好。
  • 利用 CSS transition 實現淡入淡出動畫,無需 JS 計時器。
  • 封裝為 $.fn.flash = function(cls, duration) { ... } 通用閃爍外掛。

完整範例

<ul>
  <li>項目一</li>
  <li>項目二</li>
</ul>
<script>
$('li').click(function(){ $(this).hoverEl(); });
</script>
copyright © 萬盛學電腦網 all rights reserved