最近发现一个超实用的CSS属性:pointer-events,鼠标是否穿透上层元素
前端开发中,难免会遇到一些元素被其他元素遮挡(如下图),常见的父子组件中用到的交互,无非就是事件冒泡和阻止事件冒泡,
那假如,两个元素不是父子组件的关系呢?是兄弟组件呢?想要点击box2,刚好又被box1元素挡住,无法实现点击效果
.box1 {
position: absolute;
top: 0;
width: 270px;
line-height: 270px;
z-index: 1;
background-color: rgba(255, 194, 204, 0.5);
}
.box2 {
position: absolute;
top: 0;
width: 100px;
line-height: 100px;
background: skyblue;
}
<!-- box1将box2完全遮挡住,但是点击事件又是在box2上面 -->
<div class="box1"></div>
<div class="box2" onclick="abc()"></div>
<script>
function abc() {
console.log('box2点击事件');
}
</script>
这时候,就用的上这个属性了:pointer-events,鼠标是否可以穿透当前元素,抵达被覆盖的元素
默认值 | 描述 |
---|---|
auto | 鼠标可以点击访问该元素,默认值 |
none | 鼠标点击,该元素不做任何相应 |
inherit | 继承父级属性 |
给上述代码加上pointer-events:none;
这样,box2就不受box1的遮挡,也能响应点击事件;
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 {
position: absolute;
top: 0;
width: 270px;
line-height: 270px;
z-index: 1;
pointer-events: none;
background-color: rgba(255, 194, 204, 0.5);
}
.box2 {
position: absolute;
top: 0;
width: 100px;
line-height: 100px;
background: skyblue;
}
</style>
</head>
<body>
<!-- box1将box2完全遮挡住,但是点击事件又是在box2上面 -->
<div class="box1">box1</div>
<div class="box2" onclick="abc()">box2</div>
<script>
function abc() {
console.log('box2点击事件');
}
</script>
</body>
</html>