前端案例---自定义鼠标右键菜单
之前右击出现默认的选项菜单,使用evt.preventDefault()把默认的去掉,然后自定义右击的样式
<!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;
}
ul{
list-style: none;
width: 200px;
padding: 10px;
border: 1px solid black;
display: none;
position: absolute;
}
ul li:hover{
background: blue;
}
</style>
</head>
<body>
<ul id="list">
<li class="aaa">11111111</li>
<li class="bbb">22222222</li>
<li class="ccc">333333333</li>
</ul>
<script>
document.addEventListener("contextmenu",function(evt){
evt.preventDefault()
list.style.display = "block"
var x = evt.clientX
var y = evt.clientY
if(x >= document.documentElement.clientWidth-list.offsetWidth)
x = document.documentElement.clientWidth-list.offsetWidth
if(y >= document.documentElement.clientHeight-list.offsetHeight)
y = document.documentElement.clientHeight-list.offsetHeight
list.style.left = x + "px"
list.style.top = y + "px"
})
// 点击左键消失
document.addEventListener("click",()=>{
list.style.display = "none"
})
list.onclick = function(){
console.log("list")
}
</script>
</body>
</html>