概念
pointer-events 属性用于设置元素是否对鼠标事件做出反应。 默认值为 auto,就是元素对鼠标事件做出反应,可设置为 pointer-events: none; 表示元素忽略鼠标事件。
用最简单的话来说,只要设置了 pointer-events: none; 任何鼠标事件都将被无效化(例如:点击事件、鼠标移入移除、css 的 hover 等)。
默认值 auto
让我们上代码来看下没有设置 pointer-events: none; 的效果是什么
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#demo {
width: 200px;
height: 200px;
background-color: aqua;
text-align: center;
line-height: 200px;
}
#demo:hover {
background-color: bisque;
}
</style>
<body>
<div id="demo">我是测试的div</div>
<script>
const demo = document.getElementById('demo');
demo.onclick = e => {
console.log('点击了');
};
demo.onmouseenter = e => {
console.log('移入了');
};
demo.onmouseleave = e => {
console.log('移出了');
}
</script>
</body>
</html>
上面的代码写了一个 div 元素,我们在这个元素上绑定了点击、鼠标移入、鼠标移出这三个 js 鼠标事件,并在 css 上绑定了 hover 样式,鼠标进入会改变元素的背景色,这个就是正常我们元素对鼠标事件响应的样子。
设置值 none
接下来我们在 demo 元素上加上 pointer-events: none; 属性看一下是什么样子
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
#demo {
width: 200px;
height: 200px;
background-color: aqua;
text-align: center;
line-height: 200px;
pointer-events: none;
}
#demo:hover {
background-color: bisque;
}
</style>
<body>
<div id="demo">我是测试的div</div>
<script>
const demo = document.getElementById('demo');
demo.onclick = e => {
console.log('点击了');
};
demo.onmouseenter = e => {
console.log('移入了');
};
demo.onmouseleave = e => {
console.log('移出了');
}
</script>
</body>
</html>
上面代码仅增加了一行 pointer-events: none; 代码中的 js 鼠标事以及 hover 全部都无效化了,元素没有对以上操作做出反应(鼠标点击选中文字是可以的)
应用场景
- 一个元素覆盖在另一个元素,为上面一个元素添加 pointer-events: none; 使其点击上面的元素触发下面元素的点击事件。
- 按钮添加防抖自定义指令时,可以在禁用期间设置 pointer-events: none; 使其点击事件被穿透,从而避免多次触发按钮事件。