根据MDN
如果在一个元素上按下按钮,然后在另一个元素上释放按钮,则会在包含这两个元素的最特定祖先元素上触发该事件。
有办法避免这种情况吗?
这是我的codepen,我正在尝试模拟带有消除遮罩的模态
如果工作正常,但是如果单击“模式”(红色)并将鼠标指针拖到外部并释放,则会调用关闭功能。如何避免这种行为?
function handleClose(e) {
alert('close');
}
function handleModal(e){
e.preventDefault();
e.stopPropagation();
console.log(e)
}
.modal {
height: 2000px;
background-color: red;
width: 250px;
margin: auto;
}
.container {
z-index: 100;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow-y: scroll;
}
.mask {
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgb(123, 123, 123, 0.5);
z-index: 0;
overflow: hidden;
}
body {
overflow: hidden;
height: 100%;
}
html {
height: 100%;
}
<div class="container">
<div class="mask" onClick="handleClose(event);">
<div class="modal" onClick="handleModal(event);"> fldsjfld </div>
</div>
</div>
dfs df sdf asd fsadg
答案 0 :(得分:0)
您可以使用onmousedown
事件监听器来代替onclick
。
通过使用onmousedown
,该功能将在您单击时运行,而不是在释放单击时运行。
检查您更新的代码笔HERE
这是一个有效的代码段:
function handleClose(e) {
alert('close');
}
function handleModal(e){
e.preventDefault();
e.stopPropagation();
console.log(e)
}
.modal {
height: 2000px;
background-color: red;
width: 250px;
margin: auto;
}
.container {
z-index: 100;
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
overflow-y: scroll;
}
.mask {
left: 0;
right: 0;
top: 0;
bottom: 0;
background: rgb(123, 123, 123, 0.5);
z-index: 0;
overflow: hidden;
}
body {
overflow: hidden;
height: 100%;
}
html {
height: 100%;
}
<div class="container">
<div class="mask" onmousedown="handleClose(event);">
<div class="modal" onmousedown="handleModal(event);"> fldsjfld </div>
</div>
</div>
dfs df sdf asd fsadg