代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<!--
* @Author: Han
* @Date: 2021-10-27 17:34:01
* @LastEditors: Han
* @LastEditTime: 2021-10-27 17:36:35
* @FilePath: \Projectc:\Users\Han\Desktop\Untitled-1.html
-->
<!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>一张图片或Div不同位置点击事件</title>
<style>
div {
position: relative;
margin: 100px auto;
width: 332px;
height: 332px;
border: 1px solid black;
}

div::before,
div::after {
content: '';
position: absolute;
background: black;
}

div::before {
height: 1px;
width: 100%;
top: 166px;
}

div::after {
height: 100%;
width: 1px;
left: 166px;
}
</style>
</style>
</head>

<body>
<div>
</div>
<script>
const btn = document.querySelector('div');
btn.onclick = function (e) {
alert(`点击了${e.offsetX >= 166 ? '右' : '左'}${ e.offsetY >= 166 ? '下' : '上'}`)
};
</script>
</body>

</html>