单击对象时停止mouseleave

如果我想要鼠标输入div,则会显示一个元素,然后当mouseleave时,元素消失。

我在mouseenter中有一个clickfunction,所以点击时会有一个下拉菜单。

我希望下拉菜单和元素即使在mouseleaves时也能保持活动状态。 因此,当有点击事件时,我希望鼠标在这种情况下不适用。 用户必须再次单击该元素或页面上的任何位置,以使元素和下拉菜单消失。

但是我想保持mouseleavefunction正常工作,所以如果用户鼠标移动div,该元素将显示,他们可以再次点击它。

我目前有类似的东西,但我不知道如何使鼠标在点击时不适用

$(".div").mouseenter(function(){ $(".element",this).show(); $(".element").click(function(){ $(".dropdown").show(); return false; }); }).mouseleave(function(){ $(".element",this).hide(); }); 

编辑:

HTML

 
boxed element

您可以设置自定义属性以将项目标记为已单击。 mouseleave事件处理程序可以在隐藏元素之前检查此自定义属性的值。

即:像:

 $(".div").mouseenter(function(){ $(".element",this).show(); $(".element").click(function(){ $(".dropdown").show(); // set custom attribute for marking this one as clicked $(this).attr('clicked', 'yes'); return false; }); }).mouseleave(function(){ // check custom attribute before hiding the element if($(this).attr('clicked') != 'yes') { $(".element",this).hide(); } }); 

这对我有用

 $("#id").click(function(){ $("#id").off("mouseleave"); }); 

如果你使用1.7+,你可以使用jQuery的新开/关方法

就像是:

 $(".div").on('mouseenter', function(){ showElm(); $(".element").click(function(){ $(".div").off('mouseleave', hideElm); $(".dropdown").show(); return false; }); }); $(".div").on('mouseleave', hideElm); $(document).on('click', hideElm); function hideElm() { $(".element, .dropdown").hide(); } function showElm() { $(".element").show(); } 

小提琴: http : //jsfiddle.net/fSjtm/

可能需要一些tweeking,但它会给你一个大致的想法。

使用event.stopPropagation();

这样更好,因为您可以在元素上使用链接

 $(".div").on('mouseenter', function(){ showElm(); $(".element").click(function(event){ $(".div").off('mouseleave', hideElm); $(".dropdown").show(); event.stopPropagation(); }); }); $(".div").on('mouseleave', hideElm); $(document).on('click', hideElm); function hideElm(event) { $(".element, .dropdown").hide(); } function showElm(event) { $(".element").show(); } 
 .element {position: absolute; top: 20px; height: 100px; width: 100px; display:none; background: red; } .dropdown {position: absolute; top: 120px; height: 400px; width: 100px; background: blue; display:none;} 
  
HERE
boxed element

您所引用的mouseleave事件似乎是由jquery点击而不是原始mouseEvent自定义触发的。 试试这个:

 $(".div").on('mouseenter', function(){ $(".element").on('click', function(){ ... }); }); $(".div").on('mouseleave', function(event){ if(typeof(e.originalEvent) != 'undefined'){ // only when mouseleave is the original event. } });