JQuery:当在子对象上进行mousedown时,只触发父对象而不是子对象?

时间:2014-09-26 05:09:17

标签: javascript jquery html

我只想在子元素上mousedown / mousemove时触发父div而不是child。我正在设计一个带有限制区域的对象说[square],当我在区域内移动慢速鼠标时工作正常,但是当我快速移动它移出限制区域时,如何在禁区内进行操作?我不想使用任何插件。

1 个答案:

答案 0 :(得分:1)

停止子事件的立即传播,手动触发父事件

$(".restricted.child").on('mousedown', function (e) {
    e.stopImmediatePropagation();
    $(this).closest(".parent").trigger('mousedown');
});

修改

根据您更新的说明,我认为这是您可以获得的最接近的。

触发了子事件,没有解决这个问题,但您可以使用event.stopImmediatePropagation()来阻止其他处理程序执行,并防止事件冒泡DOM树。

然后,您可以在父级上触发相同的事件。有很多方法可以定位父级,但我使用.closest()方法来定位这个孩子最近的父级.parent



$(".restricted.child").on('mousedown', function (e) {
    e.stopImmediatePropagation();
    $(this).closest(".parent").trigger('mousedown');
});

$(".child").on('mousedown', function (e) {
    $(this).toggleClass('child-alt');
});

$(".parent").on('mousedown', function (e) {
    $(this).toggleClass('parent-alt');
});

.wrapper {
    position: relative;
    float: left;
    width: 200px;
    margin: 10px;
}

.parent {
    position: relative;
    width: 200px;
    height: 200px;
    transition: all 1s ease-out;
    background-color: ForestGreen;
}

.child {
    position: relative;
    top: 50px;
    left: 50px;
    width: 100px;
    height: 100px;
    transition: all 1s ease-out;
    background: DodgerBlue;
}

.parent-alt {
    border-radius: 200px;
    background-color: Plum;
}

.child-alt {
    border-radius: 100px;
    background-color: Chocolate;
}

h2 {
    margin: 0 0 10px 0;
    font-family: 'Arial Narrow', Arial, sans-serif;
    line-height: 1em;
}

p {
    font-family: Tahoma, Verdana, Segoe, sans-serif;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <h2>Restricted<br />propagation</h2>
    <div class="parent">
        <div class="restricted child"></div>
    </div>
    <p>Restricted child's event is halted, but the parent event is triggered manually.</p>
</div>

<div class="wrapper">
    <h2>Natural<br />propagation</h2>
    <div class="parent">
        <div class="child"></div>
    </div>
    <p>Unrestricted child's event will fire and the parent event is fired naturally.</p>
</div>
&#13;
&#13;
&#13;