如果在mouseover事件中触发了mousedown,则立即返回并且不执行链式mouseout事件

时间:2012-05-02 20:14:34

标签: javascript jquery javascript-events mouseover mousedown

不知道如何解决这个问题,但基本上我写了一个工具提示插件,它可以删除mouseout或mousedown上的工具提示。

如果触发了mousedown事件,它将删除$that.parent(),这很好,这将删除工具提示,但如果用户也触发了mouseout事件(他们将因为mouseover和mouseout事件是当前已链接),它将删除另一个我不想要的DOM元素。所以基本上我想知道这是否可能:

$that.on('mouseover', function() {

    // If this event is triggered within the mouseover event, don't run the chained mouseout event
    $that.on('mousedown', function() {
        $that.parent().next().fadeOut(100).remove();
        return false;
    });
}).mouseout(function() {
  // If they clicked above, don't run this
    $that.parent().next().fadeOut(100).remove();
});​

据我所知,在不使用全局变量的情况下,很难访问该mousedown事件中的clicked布尔集,例如:

$that.on('mouseover', function() {
    clicked = false;
    // If this event is triggered within the mouseover event, don't run the chained mouseout event
    $that.on('mousedown', function() {
        clicked = true;
        $that.parent().next().fadeOut(100).remove();
        return false;
    });
}).mouseout(function() {
    // If they clicked above, don't run this
    if (clicked) {
        $that.parent().next().fadeOut(100).remove();
    }
});​

关于如何优雅地构建这个的任何想法?

编辑:$ that.parent()。next()中的元素只是<div class="js-tooltip"><span>Tooltip text</span></div>

但这应该是无关紧要的,因为我想知道如果在不使用全局变量的情况下触发mousedown,是否可以从鼠标悬停功能返回。

2 个答案:

答案 0 :(得分:1)

您不需要mouseover

$that.on('mouseleave mouseup', function(e) {
     if( e.type === 'mouseleave'){
         // do the mouseleave stuff
     }else{
         // do the mouseup stuff
     }
});​

正如你所说,如果元素是动态创建的,你应该使用:

$(document).on('mouseleave mouseup', $that, function(e) {

答案 1 :(得分:0)

您是否考虑过像这样使用类过滤器?

$that.parent().next('.js-tooltip').fadeOut(100).remove();

如果下一个不是工具提示,这根本不会做任何事情,据我所知,这应该可以解决问题。

使用您提出的方法,$that.clicked = false更清楚。

或者如何(如果你想保留鼠标悬停 - 这只是为了证明原理;我不确定它是否会像这样工作):

$that.on('mouseover', function() {

    // If this event is triggered within the mouseover event, don't run the chained mouseout event
    $that.on('mousedown mouseout', function() {
        $that.parent().next().fadeOut(100).remove();
        $that.off('mousedown mouseout'); //prevent that happening again
        return false;
    });
});
相关问题