javascript 停止从单击处理程序传播 mousedown/mouseup

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8875070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:50:50  来源:igfitidea点击:

Stopping propagation of mousedown/mouseup from a click handler

javascriptjquerymouseevent

提问by Josh Smith

Here's a DEMO.

这是一个演示

I have two divs, an inner and an outer:

我有两个divs,一个内部和一个外部:

<div id="outer">
    <div id="inner"></div>
</div>

With some CSS so you can see which is which:

使用一些 CSS,您可以看到哪个是哪个:

#outer {
    width: 250px;
    height: 250px;
    padding: 50px;
    background: yellow;
}

#inner {
    width: 250px;
    height: 250px;
    background: blue;
}

I try to stop propagation of mousedownand mouseupevents from within a clickhandler like so:

我尝试停止从处理程序中传播mousedownmouseup事件,click如下所示:

$('#inner').on('click', function(e) {
    e.stopPropagation();
    $(this).css({'background': 'green'});
    return false;
});

$('#outer').on('mousedown', function(e) {
    $(this).css({'background': 'green'});
});

$('#outer').on('mouseup', function(e) {
    $(this).css({'background': 'yellow'});
});

This doesn't seem possible. What does work is calling .stopPropagationfrom within other mousedownand mouseupcalls, as shown here (another DEMO):

这似乎不可能。有效的是.stopPropagation从其他内部调用mousedownmouseup调用,如下所示另一个演示)

$('#inner').on('mousedown', function(e) {
    e.stopPropagation();
    return false;
});

$('#inner').on('mouseup', function(e) {
    e.stopPropagation();
    return false;
});

I may have already answered my own question, but I'm not sure if my approach is the best or most reasonable. Is this the right way to stop an event bubbling up to a mousedownand mouseup?

我可能已经回答了我自己的问题,但我不确定我的方法是最好的还是最合理的。这是阻止事件冒泡到 a mousedownand的正确方法mouseup吗?

回答by Jeff

Yes. Since mouseclick and mousedown/mouseup are different events, you can't get at one from the other at all - you have to do it from within your own mousedown/mouseup handlers. What you can do is refactor that into a generic method to use in both places:

是的。由于 mouseclick 和 mousedown/mouseup 是不同的事件,因此您根本无法从另一个事件中获得一个 - 您必须在您自己的 mousedown/mouseup 处理程序中进行。您可以做的是将其重构为在两个地方都使用的通用方法:

stopPropagation('#inner', 'mousedown');
stopPropagation('#inner', 'mouseup');

function stopPropagation(id, event) {
    $(id).on(event, function(e) {
        e.stopPropagation();
        return false;
    });
}