我们有时候在开发过程中会有自定义右键菜单,替换掉浏览器默认右键菜单的想法,那么如何实现呢?话不多说,上代码:
Html代码:
<!DOCTYPE html>
<html lang="zh">
<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>
<link rel="shortcut icon" href="https://llyth.cn/img/favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="action_area" id="action_area">触发区域</div>
<ul id="custom_menu">
<li onclick="javascript:location.reload();">刷新</li>
<li onclick="javascript:location.reload();">刷新</li>
<li onclick="javascript:location.reload();">刷新</li>
<li onclick="javascript:location.reload();">刷新</li>
</ul>
<script src="index.js"></script>
</body>
</html>
CSS代码:
* {
margin: 0;
padding: 0;
}
.action_area {
width: 80%;
height: 300px;
margin: 0 auto;
border: 1px solid black;
margin-top: 200px;
font-size: 8em;
text-align: center;
line-height: 300px;
}
#custom_menu {
list-style: none;
width: 150px;
border: 1px solid #ccc;
border-bottom: none;
background-color: #fff;
position: absolute;
display: none;
}
#custom_menu li {
border-bottom: 1px solid #ccc;
padding: 5px 10px;
cursor: pointer;
}
#custom_menu li:hover {
background-color: #ccc;
}
JavaScript代码:
var custom_menu = document.getElementById("custom_menu");
var action_area = document.getElementById("action_area");
action_area.addEventListener("contextmenu", function (event) {
event.preventDefault();
custom_menu.style.display = "block";
//获取鼠标视口位置
custom_menu.style.top = event.clientY + "px";
custom_menu.style.left = event.clientX + "px";
});
document.addEventListener("click", function(event){
custom_menu.style.display = "none";
});
文件目录结构如图:
效果:
也可以对右键菜单添加一些小logo、动画等以优化交互体验。
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
Eric · 梦曦
本文地址: Html自定义鼠标右键菜单
本文地址: Html自定义鼠标右键菜单