一、鼠标事件穿透遮盖物
正常来说当有点击事件的元素被遮盖时,点击事件是不生效的,如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>鼠标事件穿透遮盖物</title>
</head>
<body>
<style>
.wrap {
position: relative;
width: 300px;
height: 300px;
display: flex;
border: 1px solid #666;
}
.center {
margin: auto;
width: 200px;
height: 200px;
background-color: greenyellow;
border: 1px solid #666;
cursor: pointer;
}
.decoration {
width: 300px;
height: 300px;
position: absolute;
left: 0;
top: 0;
background: rgba(154,205,50, 0.3);
//pointer-events: none;
}
.other-box {
width: 30px;
height: 30px;
position: absolute;
left: 5px;
top: 5px;
background-color: red;
cursor: pointer;
//pointer-events: auto;
}
</style>
<div class="wrap">
<div class="center" onclick="clickCenter()"></div>
<div class="decoration">
<div class="other-box" onclick="clickRed()"></div>
</div>
</div>
<script>
function clickCenter() {
alert('点击到中间方块了')
}
function clickRed() {
alert('点击到红色方块了')
}
</script>
</body>
</html>
此时,clickRed点击事件是生效的,但是clickCenter事件因为元素被遮盖是不生效的
当把在class decoration 样式上的 pointer-events: none注释打开,clickCenter事件现在是生效的
但是clickRed点击事件是不生效的,此时再把class other-box 样式上的 pointer-events: auto注释
打开,clickRed和clickCenter点击事件都是生效的
二、pointer-events属性介绍
auto: 与pointer-events 未指定时效果相同
none:阻止元素成为鼠标事件目标
本文探讨了HTML/CSS中鼠标事件穿透现象,通过实例展示了pointer-events属性如何影响元素的点击行为,重点讲解了'auto'和'none'模式下的事件交互,并揭示了在遮罩元素中的事件处理策略。
2486

被折叠的 条评论
为什么被折叠?



