如果在鼠标悬停事件中触发了鼠标关闭,则立即返回,并且不执行链接的鼠标退出事件

Return immediately and not execute chained mouseout event if mousedown was triggered inside mouseover event

本文关键字:鼠标 返回 执行 出事件 退出 链接 事件 悬停 如果      更新时间:2023-09-26

不知道该怎么做,但基本上我写了一个工具提示插件,它删除了mouseoutmousedown上的工具提示。

如果触发了mousedown事件,它将删除$that.parent()这很好,这会删除工具提示,但是如果用户也触发了mouseout事件(他们会这样做,因为mouseovermouseout事件当前是链接的),然后它将删除另一个我不想要的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是否可以从该mouseover函数返回。

你不需要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) {

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

$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;
    });
});