2013-09-23 34 views
0

我試圖拖延在一個元素添加和刪除類元素,當用戶將鼠標懸停:延遲添加/上的mouseenter刪除類/懸停

$('#thumbs div').mouseenter(function() {    
    $('#thumbs div').removeClass('hovered'); 
    $(this).addClass('hovered'); 
}); 

有沒有辦法做到這一點?例如,我想延遲大約0.3秒。

謝謝!

回答

0

試試這個:

$("#thumbs div").mouseenter(function() { 
     $(this).removeClass('hovered'); 
     setTimeout("addClassCustom", 300); 
}); 

function addClassCustom() { 
     $("#thumbs div").addClass('hovered'); 
} 
0
$("#thumbs div").mouseenter(function() {    
    var self = $(this);  

    self.removeClass('hovered'); 

    window.setTimeout(function() { 
     self.addClass('hovered'); 
    }, 300); 
}); 
+0

jQuery的延遲僅適用於外匯隊列,即動畫,沒有其他方法。 – adeneo

+0

嗯,我不確定這一點,也是我添加了第二個選項的原因。我會編輯。 –

0

你可以對其進行排隊:

$("#thumbs div").mouseenter(function() { 
    $(this).delay(300).queue(function(next){ 
    $('#thumbs div').removeClass('hovered'); 
    $(this).addClass('hovered'); 
    next(); 
    }); 
}); 

你可能想取消/如果鼠標離開的東西,如http://api.jquery.com/clearQueue/清除隊列。

0

你可以嘗試這樣的事情

$("#thumbs div").on('mouseenter', function() {    
    var el = $(this);  
    setTimeout(function() { 
     $('#thumbs div').removeClass('hovered'); 
     el.addClass('hovered'); 
    }, 300); 
}).on('mouseleave', function(){ 
    var el = $(this); 
    setTimeout(function() { 
     el.removeClass('hovered'); 
    }, 300); 
}); 

DEMO.