![](https://i-blog.csdnimg.cn/blog_migrate/16e4416736240ac4048b15379ff911d5.gif)
主要使用到了阻止冒泡和阻止默认事件
<!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>个性化菜单</title>
<style>
* {
padding: 0;
margin: 0;
}
.list {
width: 300px;
height: 270px;
padding-top: 20px;
border-radius: 8px;
border: 2px solid #cccccc;
box-sizing: border-box;
box-shadow: 6px 8px 6px #cccccc;
background-color: #ffffff;
position: absolute;
display: none;
}
.list > li {
width: 100%;
height: 45px;
font-size: 20px;
line-height: 45px;
text-indent: 1em;
list-style-type: none;
cursor: pointer;
}
/* .list > li:hover {
background-image: linear-gradient(to right, #b80303 2.5%, #cf94d9 2.5%);
color: white;
} */
</style>
</head>
<body>
<ul class="list">
<li>返回</li>
<li>重新加载</li>
<li>另存为(A)...</li>
<li>打印(P)...</li>
<li>查看网页源代码</li>
</ul>
<script>
// 获取到ul
var ul = document.querySelector(".list");
// 获取到每个li
var lis = document.querySelectorAll(".list > li");
// dom右键 阻止默认行为 ul出现
document.oncontextmenu = function (e) {
// 兼容IE event事件
e = e || window.event;
// 第一种阻止默认行为 右键菜单行为
event ? (event.returnValue = false) : event.preventDefault();
// 给写好的菜单显示
ul.style.display = "block";
ul.style.left = e.clientX + "px";
ul.style.top = e.clientY + "px";
// 第二种阻止默认行为方法 右键菜单行为
// return false;
};
// dom左键 ul隐藏
document.onclick = function () {
ul.style.display = "none";
};
// ul左键 阻止冒泡
ul.onclick = function (e) {
// 兼容IE event事件
e = e || window.event;
// 阻止事件冒泡
event ? (event.cancelBubble = true) : event.stopPropagation();
// ul显示
ul.style.display = "block";
};
// 遍历lis 当鼠标移动到哪个 哪个添加样式
for (var i = 0; i < lis.length; i++) {
// 当鼠标移动到哪个li 哪个li触发事件
lis[i].onmouseenter = function () {
// 动态给li添加样式 也可以直接在css里面写好
this.style.backgroundImage =
"linear-gradient(to right, #b80303 2.5%, #cf94d9 2.5%)";
this.style.color = "white";
};
// 当鼠标离开到哪个li 哪个li触发事件
lis[i].onmouseleave = function () {
// 动态清除li样式
this.style.backgroundImage = "none";
this.style.color = "black";
};
}
// 点击返回
lis[0].onclick = function () {
history.forward();
};
// 点击刷线
lis[1].onclick = function () {
location.reload();
};
</script>
</body>
</html>
就可以设置自己想要的个性化菜单了