实现右键菜单
<!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>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.menu {
background-color: white;
width: 140px;
border: 1px solid #ccc;
border-radius: 5px;
overflow: hidden;
position: absolute;
box-shadow: 2px 2px 8px 1px rgba(0, 0, 0, 0.2);
display: none;
}
.menu li {
list-style: none;
width: 100%;
}
.menu li span {
display: inline-block;
text-decoration: none;
color: #ccc;
width: 100%;
font-weight: 700;
font-size: 17px;
padding: 10px 4px;
text-align: center;
cursor: pointer;
box-sizing: border-box;
}
.menu li span:hover {
background: #eee;
color: #1826f0;
}
</style>
</head>
<body style="background-color: rgba(13, 228, 163, 0.452)">
<ul class="menu" id="menu">
<li><span>复制</span></li>
<li><span>粘贴</span></li>
<li><span>刷新</span></li>
<li><span>其他功能1</span></li>
<li><span>其他功能2</span></li>
</ul>
<h1 style="margin: 10% 40%">右键菜单</h1>
</body>
<script>
window.oncontextmenu = function (e) {
if (e.clientX + 140 <= innerWidth) {
var x = e.clientX;
} else {
var x = e.clientX - 138;
}
if (e.clientY + 140 <= innerHeight) {
var y = e.clientY;
} else {
var y = e.clientY - 208;
}
let menu = document.querySelector("#menu");
console.log("menu: ", menu);
menu.style.left = x + "px";
menu.style.top = y + "px";
menu.style.display = "block";
e.preventDefault();
};
document.querySelector("#menu").onclick = function () {
document.querySelector("#menu").style.display = "none";
};
window.onclick = function () {
document.querySelector("#menu").style.display = "none";
};
</script>
</html>