我希望只阻止.box1和.box2区域内的点击事件,并且鼠标光标样式不会改变。我当前的代码如下,我在其中检查 e.target 的值,但这也阻止了 .boxs 区域内的单击事件。此外,我已将指针事件设置为无,但鼠标光标样式仍然发生变化。我注意到有一个类似的问题,但对于我的问题没有更好的答案。 56886001
const wrap = document.querySelector('.wrap');
wrap.addEventListener('click', (event) => {
if (event.target === wrap) {
console.log('wrap');
}
});
.wrap {
width: 500px;
height: 500px;
background-color: lightcyan;
cursor: pointer;
}
.boxs {
width: 300px;
border: 2px solid black;
}
.box1 {
width: 250px;
height: 250px;
background-color: bisque;
pointer-events: none;
}
.box2 {
width: 250px;
height: 250px;
background-color: azure;
pointer-events: none;
}
<div class="wrap">
<div class="boxs">
<div class="box1"></div>
<div class="box2"></div>
</div>
</div>
这里有一些可能对你有用:
从两个框中删除
pointer-events: none;
,因为您确实希望它们捕获点击事件,因此您可以阻止它们。
给两个框
cursor: initial
,以便光标在悬停时保持正常状态。
为两个框和
event.stopPropagation()
添加点击事件监听器,这样点击事件就不会冒泡到.wrap
。
const wrap = document.querySelector('.wrap');
wrap.addEventListener('click', (event) => {
console.log('wrap');
});
document.querySelectorAll('.boxs > *').forEach(box => box.addEventListener('click', event => {
event.stopPropagation();
}));
.wrap {
width: 500px;
height: 500px;
background-color: lightcyan;
cursor: pointer;
}
.boxs {
width: 300px;
border: 2px solid black;
}
.box1 {
width: 250px;
height: 250px;
background-color: bisque;
}
.box2 {
width: 250px;
height: 250px;
background-color: azure;
}
.boxs > * {
cursor: initial;
}
<div class="wrap">
<div class="boxs">
<div class="box1"></div>
<div class="box2"></div>
</div>
</div>