示例
设计思路:
- 禁用原始鼠标右键菜单;
- 使用 HTML 元素搭建一个菜单列表,并响应鼠标点击事件。
<!DOCTYPEhtml><html><head><metacharset="utf-8"/><title>Custom Context Menu</title><styletype="text/css">*{box-sizing: border-box;margin: 0;padding: 0;}body{background-color: gainsboro;}.context-menu{background-color:rgba(240, 240, 240, 1);border-color:rgba(0, 0, 0, 0.4);border-style: solid;border-width: 1px;box-shadow: 2px 2px 2px 1px rgba(0, 0, 0, 0.2);padding: 4px;position: fixed;width: 200px;}.context-menu-item{--height: 30px;cursor: pointer;height:var(--height);line-height:var(--height);list-style: none;padding-left: 5px;vertical-align: middle;transition-duration: 0.8s;transition-property: background-color;user-select: none;}.context-menu-item:hover{background-color:rgba(255, 255, 255, 1);}p{margin: 10px;}</style></head><body><p><span>The oncontextmenu property of the GlobalEventHandlers mixin is an event handler that processes contextmenu events.</span><br><span>The contextmenu event typically fires when the right mouse button is clicked on the window. Unless the default behavior is prevented, the browser context menu will activate.</span></p><p><span>The onmouseup property of the GlobalEventHandlers mixin is an event handler that processes mouseup events.</span><br><span>The mouseup event fires when the user releases the mouse button.</span></p><p><span>In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognized.</span></p></body><scripttype="text/javascript">// 鼠标左、右键标志,参考:constMOUSE_LEFT_BUTTON=0constMOUSE_RIGHT_BUTTON=2
window.onload=(event)=>{
console.log(event);main();}functionmain(){let menu =null;
window.oncontextmenu=(event)=>{// 禁用原始鼠标右键菜单// console.log(event);// event.preventDefault();returnfalse;}
document.onmouseup=(event)=>{
console.log(event);// console.log(event.clientX, event.clientY);if(event.button ===MOUSE_RIGHT_BUTTON){// 鼠标右键if(menu !==null){
document.body.removeChild(menu);// 移除菜单}
menu = document.createElement("ul");// 菜单
menu.className ="context-menu";
menu.style.top = event.clientY +"px";
menu.style.left = event.clientX +"px";const item0 = document.createElement("li");// 菜单子项 0
item0.innerText ="个性化";
item0.className ="context-menu-item";const item1 = document.createElement("li");// 菜单子项 1
item1.innerText ="显示设置";
item1.className ="context-menu-item";
menu.appendChild(item0);// 添加菜单子项
menu.appendChild(item1);
document.body.appendChild(menu);// 添加(展现)菜单}elseif(event.button ===MOUSE_LEFT_BUTTON){// 鼠标左键if(menu !==null){
document.body.removeChild(menu);// 移除菜单
menu =null;}const target = event.target;// 获取被鼠标左键点击的目标if(target.className ==="context-menu-item"){alert(target.innerText);}}}
document.onmousedown=(event)=>{// console.log(event);}}</script></html>

发布评论