![简约自定义右键菜单模板](https://img2020.cnblogs.com/blog/1975550/202112/1975550-20211227181728748-1786571786.png)
简约自定义右键菜单模板、
前言:
1. 我借鉴了网络上的代码
2. 代码没有使用JQuery或者vue、react等,使用原生JS,便于后期各种版本直接使用
3. 这个是用于修改浏览器自带的右键菜单,改为自定义的,可以实现更多的功能。
简约自定义右键菜单模板
前言:
1. 我借鉴了网络上的代码
2. 代码没有使用JQuery或者vue、react等,使用原生JS,便于后期各种版本直接使用
3. 这个是用于修改浏览器自带的右键菜单,改为自定义的,可以实现更多的功能。
效果:
![image](https://img2020.cnblogs.com/blog/1975550/202112/1975550-20211227181437413-973591033.gif)
代码:
<!DOCTYPE html>
<html lang="ch">
<head>
<meta charset="UTF-8">
<meta name ="viewport" content ="width = device-width" />
<title>gxg</title>
</head>
<style lang="css">
/*右键菜单*/
#contextmenu {
visibility:hidden;
position: absolute;
width: 200px;
margin: 0;
padding: 0;
background: #FFFFFF;
border-radius: 5px;
list-style: none;
box-shadow:
0 15px 35px rgba(50,50,90,0.1),
0 5px 15px rgba(0,0,0,0.07);
overflow: hidden;
z-index: 999999;
}
#contextmenu li {
border-left: 3px solid transparent;
transition: ease .2s;
}
#contextmenu li a {
display: block;
padding: 10px;
color: #808c92;
text-decoration: none;
transition: ease .2s;
}
#contextmenu li:hover {
background: #adb;
border-left: 3px solid #30b8ea;
}
#contextmenu li:hover a {
color: #FFFFFF;
}
</style>
<body>
<!-- 默认隐藏 -->
<ul id="contextmenu">
<li><a href="/">选项一</a></li>
<li><a href="/">选项二</a></li>
<li><a href="/">选项三</a></li>
</ul>
<script type="text/javascript">
//设置右键菜单
window.onload=function(){
//获取contextmenu尺寸
var menuWidth = document.getElementById("contextmenu").offsetWidth;
var menuHeight = document.getElementById("contextmenu").offsetHeight;
document.oncontextmenu = function(e){
//获取屏幕宽度、高度
var winWidth = window.innerWidth;
var winHeight = window.innerHeight;
//获取点击位置
var posX = e.pageX;
var posY = e.pageY;
//保持右键菜单在屏幕内:
if(posX + menuWidth + 10 >= winWidth&& posY + menuHeight + 10 >= winHeight){
//超出了右下方:
posLeft = posX - menuWidth - 10 + "px";
posTop = posY - menuHeight - 10 + "px";
}
else if(posX + menuWidth + 10 >= winWidth){
//超出了右侧:
posLeft = posX - menuWidth - 10 + "px";
posTop = posY + 10 + "px";
}
else if(posY + menuHeight + 10 >= winHeight){
//超出了底部:
posLeft = posX + 10 + "px";
posTop = posY - menuHeight - 10 + "px";
}
else {
//默认右下方显示:
posLeft = posX + 10 + "px";
posTop = posY + 10 + "px";
};
document.getElementById("contextmenu").style.cssText = 'visibility:visible;left: '+posLeft+';top: '+posTop;
return false;//取消浏览器自带的右键菜单
};
document.onclick=function(){
document.getElementById("contextmenu").style.display = 'none'//点击其他位置隐藏
};
};
</script>
</body>
</html>