我只想在子元素上 mousedown/mousemove 时触发父 div 而不是子元素。我正在设计一个带有限制区域的对象,例如[正方形],当我在区域内缓慢移动鼠标时它工作正常,但是当我快速移动时它会移出限制区域,我怎样才能使其进入限制区域?我不想使用任何插件。
最佳答案
停止子事件的立即传播,手动触发父事件
$(".restricted.child").on('mousedown', function (e) {
e.stopImmediatePropagation();
$(this).closest(".parent").trigger('mousedown');
});
编辑:
根据您更新的描述,我认为这是您可以获得的最接近的结果。
子事件被触发,无法解决这个问题,但您可以使用 event.stopImmediatePropagation()
防止其他处理程序被执行并防止事件在 DOM 树中冒泡。
然后您可以在父级上触发相同的事件。有多种方法可以定位父级,但我使用了 .closest()
方法仅针对具有 .parent
的该 child 最近的 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>
关于javascript - JQuery:当鼠标按下子对象时,仅触发父对象而不触发子对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26052442/