點擊元素時,暫時加上自訂屬性 hover="on",搭配 CSS 屬性選擇器套用高亮樣式,延遲移除屬性還原外觀。
$.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);
}
});
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'),語意更清晰、效能更好。transition 實現淡入淡出動畫,無需 JS 計時器。$.fn.flash = function(cls, duration) { ... } 通用閃爍外掛。<ul>
<li>項目一</li>
<li>項目二</li>
</ul>
<script>
$('li').click(function(){ $(this).hoverEl(); });
</script>