Custom html element right mouse button menu
Realization of ideas
When the trigger contextmenu event, cancel the default behavior (that is, to prevent the browser's own menu is displayed), the event object to obtain the right to determine the position of the mouse click, as the display menu of left and top values
Coding
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
window.onload = function(){
var menu = document.getElementById('menu');
document.body.oncontextmenu = function (e) {// custom mouse event handler body element
var e = e || window.event;
e.preventDefault (); // prevent the system does not support right-click menu IE8-
// display menu to adjust the custom location
let scrollTop =
document.documentElement.scrollTop || document.body.scrollTop; // Get the vertical position of the slider
let scrollLeft =
document.documentElement.scrollLeft || document.body.scrollLeft; // Gets the horizontal scroll bar position
menu.style.display = 'block';
menu.style.left = e.clientX + scrollLeft + 'px';
menu.style.top = e.clientY + scrollTop + 'px';
}
// hide the menu when you click the mouse elsewhere
document.onclick = function(){
menu.style.display = 'none';
}
}
</script>
<style>
*{
margin: 0;
padding: 0;
}
p{
margin-top: 200px;
}
ul li{
list-style-type: none;
margin: 10px 0;
text-align: center;
}
#menu{
border:1px solid #ccc;
background: #eee;
position: absolute; // setup menu to absolute position
width: 100px;
height: 120px;
display: none;
}
</style>
</head>
<body style="overflow:auto">
<Div id = "box" style = "height: 5000px; width: 5000px"> let the body element scroll bar appears with the div </ div>
<div id="menu">
<ul>
<li><a href="#">分享</a></li>
<li><a href="#">收藏</a></li>
<li><a href="#">举报</a></li>
</ul>
</div>
</body>
</html>
实现效果