2015-02-12 61 views
1

我想使用JQuery在鼠標懸停上顯示一個字符,但隱藏在mouseleave上。但是,當單擊元素時,我希望角色保持到另一個元素被點擊。這將一直工作,直到一個元素被點擊掉,然後你再次將其移動。 mouseleave功能不再有效。當元素使用點擊功能,然後忽略mouseleave

例這裏http://jsfiddle.net/z5v25yhL/

$('.sidecategory').on({ 
    mouseover: function(){ 
     $(this).next("span").show("fast"); 
    }, 
    mouseleave: function(){ 
     $(this).next("span").hide("fast"); 
    }, 
    click: function(){ 
     $('.sidecategory').not(this).next("span").hide(); 
     $(this).off('mouseleave'); 
    } 
}); 

回答

0

這是因爲你每次點擊一個元素時取出mouseleave事件:

$(this).off('mouseleave'); 

爲了避免這種情況,你可以改爲添加一個類的元素以選擇它。

mouseleave事件中,排除此類.selected類,然後在單擊某個元素時從所有元素中刪除.selected類。這樣做,您不再需要像以前那樣去除mouseleave事件。

Updated Example

$('.sidecategory').on({ 
    mouseover: function() { 
     $(this).next("span").show("fast"); 
    }, 
    mouseleave: function() { 
     $(this).not('.selected').next("span").hide("fast"); 
    }, 
    click: function() { 
     $('.sidecategory').removeClass('selected').not(this).next("span").hide(); 
     $(this).addClass('selected'); 
    } 
}); 
+1

這是完美的感謝! – gdkawb 2015-02-12 04:11:18

0

使用類是更好的解決方案,但它可以與上進行開/關,以及:

http://jsfiddle.net/z5v25yhL/1/

var selected; 
var mleave = function() { 
    $(this).next("span").hide("fast"); 
}; 

$('.sidecategory') 
    .on('mouseover', function() { 
     $(this).next("span").show("fast"); 
    }).on('mouseleave', mleave).on('click', function() { 
     if(selected) { 
      $(selected).on('mouseleave', mleave); 
      $(this).off('mouseleave'); 
      $('.sidecategory').not(this).next("span").hide(); 
     } else { 
      $(this).off('mouseleave'); 
      $('.sidecategory').not(this).next("span").hide();    
     } 
     selected = this; 
    });