(另一种笔记里找)
自定义右键菜单
- contextmenu 右键菜单事件
- e.preventDefault()/return false 阻止默认事件
- e.clientX/e.clientY 鼠标位置获取
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>自定义右键</title>
<style>
body {
width: 100vw;
height: 100vh;
background: url(./imgs/bg.png) no-repeat;
background-size: 100% 100%;
position: relative;
}
#list {
margin: 0;
padding: 0;
list-style: none;
width: 180px;
height: 200px;
position: fixed;
background-color: #fff;
display: none;
}
#logo {
width: 200px;
height: 48px;
background: url(./imgs/logo.png) no-repeat;
margin: 50px auto;
position: absolute;
left: 50%;
margin-left: -100px;
top: 50px;
}
#list li {
width: 100%;
height: 50px;
line-height: 50px;
text-indent: 56px;
color: #f5726c;
}
#list li:nth-child(1) {
background: url(./imgs/download.png) no-repeat 20px 16px;
}
#list li:nth-child(2) {
background: url(./imgs/remove-icon.png) no-repeat 20px 16px;
}
#list li:nth-child(3) {
background: url(./imgs/move-icon.png) no-repeat 20px 15px;
}
#list li:nth-child(4) {
background: url(./imgs/rename-icon.png) no-repeat 20px 14px;
}
#list li:hover {
background-color: #fde9e9;
color: #e6423c;
}
</style>
</head>
<body>
<div id="logo"></div>
<ul id="list">
<li>下载</li>
<li>删除</li>
<li>移动到</li>
<li>重命名</li>
</ul>
<script src="./fns.js"></script>
<script>
{
let list = document.querySelector("#list");
// contextmenu 右键菜单事件
document.addEventListener("contextmenu",(e)=>{
/*
e.clientX/e.clientY 相对于可视区的鼠标位置
e.pageX/e.pageY 相对于页面的鼠标位置
*/
css(list,"left",e.clientX);
css(list,"top",e.clientY);
css(list,"display","block");
e.preventDefault();
});
document.addEventListener("click",()=>{
css(list,"display","none");
});
}
</script>
</body>
</html>