停止从单击处理程序传播mousedown / mouseup [英] Stopping propagation of mousedown/mouseup from a click handler

查看:126
本文介绍了停止从单击处理程序传播mousedown / mouseup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个演示

Here's a DEMO.

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

I have two divs, an inner and an outer:

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

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

With some CSS so you can see which is which:

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

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

我试图阻止传播 mousedown mouseup 来自点击处理程序中的事件,如下所示:

I try to stop propagation of mousedown and mouseup events from within a click handler like so:

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

这似乎不太可能。什么工作是从其他 mousedown mouseup .stopPropagation c>通话,如另一个DEMO)

This doesn't seem possible. What does work is calling .stopPropagation from within other mousedown and mouseup calls, as shown here (another DEMO):

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

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

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

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 mousedown and mouseup?

推荐答案

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

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:

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

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

这篇关于停止从单击处理程序传播mousedown / mouseup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆