先看效果图(我没有做美化,简陋了亿点点)。
然后我先讲解一下大概的逻辑: 在用户右键时,获取其右键的位置,然后在用户右键的位置展示出右键菜单。在用户左键时,关闭右键菜单。
在用户右键的位置展示出右键菜单这一步很简单,只需要添加一个绝对定位的盒子,然后将这个盒子移动到右键的位置即可。
那么请看代码:
1 2 3 4 5 6 7 8 9 10 11 12
| <!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> </head> <body> <script src="./test.js"></script> </body> </html>
|
这是js代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
let rightMenuDiv = document.createElement("div");
let rightMenuCount = 0;
rightMenuDiv.style.backgroundColor = "red"; rightMenuDiv.style.position = "absolute";
rightMenuDiv.addEventListener("mousedown", (event)=>{event.stopPropagation();})
let rightMenuChildLink = document.createElement("a"); rightMenuChildLink.appendChild(document.createTextNode("www.gray-ice.com")); rightMenuChildLink.setAttribute("href", "https://www.gray-ice.com"); rightMenuDiv.appendChild(rightMenuChildLink);
function showRightMenu(x, y) { document.body.appendChild(rightMenuDiv); rightMenuDiv.style.left = String(x) + "px"; rightMenuDiv.style.top = String(y) + "px"; }
document.addEventListener("contextmenu", function(event){ console.log(event); event.preventDefault(); showRightMenu(event.pageX, event.pageY); rightMenuCount = 1; })
document.addEventListener("mousedown", function(event){ if(rightMenuCount) { if(event.button === 0) { document.body.removeChild(rightMenuDiv); rightMenuCount = 0; } } })
function create100P() { let str = ""; for(let i = 0; i < 100; i++) { str += `<p>${i}</p>\n`; } let ps = document.createElement("div"); document.body.appendChild(ps); ps.innerHTML = str; } create100P();
|
就是这样。
本篇完。