原理:
1. pointer-events:none; 元素永远不会成为鼠标事件的target。但是,当其后代元素的pointer-events属性指定其他值时,鼠标事件可以指向后代元素,在这种情况下,鼠标事件将在捕获或冒泡阶段触发父元素的事件侦听器。
2.1 document.addEventListener('click', function (e) {}) 给document监听,进而判断
2.2 'A' != e.target.nodeName && 'BUTTON' != e.target.nodeName && 'INPUT' != e.target.nodeName 判断元素,排查元素(比如点击的是button,就不触发画圆函数)
代码: 点击页面,在画布就可以画圆,除了a,button,input,textarea..之类可点击/聚焦(有点击事件的标签)的标签
<!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>
<style>
* {
margin: 0;
padding: 0;
}
body,
html {
width: 100%;
height: 100%;
}
#box {
position: fixed;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
pointer-events: none;
}
#cvs {
background-color: lightyellow;
}
.content {
width: 100%;
height: 100%;
background-color: antiquewhite;
}
.content button {
float: right;
display: block;
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div id="box">
<canvas id="cvs" height="200" width="200"></canvas>
</div>
<div class="content">
<button>按钮</button>
</div>
</body>
<script>
var box = document.getElementById('boxa');
var cvs = document.getElementById('cvs');
var ctx = cvs.getContext('2d');
function draw() {
ctx.beginPath();
ctx.arc(100, 100, 100, 0, Math.PI * 2, true);
ctx.lineWidth = 5;
ctx.strokeStyle = 'red';
ctx.stroke();
ctx.closePath();
}
function closeDraw() {
ctx.clearRect(0, 0, 200, 200);
}
document.addEventListener('click', function (e) {
console.log(e.target.nodeName);
if ('A' != e.target.nodeName && 'BUTTON' != e.target.nodeName && 'INPUT' != e.target.nodeName) {
draw();
setTimeout(function () {
closeDraw();
}, 500)
}
})
</script>
</html>