On the Web, there is usually no need for a right-click menu, and each browser also has its own right-click menu. But for some special web pages, right-click menus are needed to increase user experience, such as Baidu Music and QQ Mailbox. I believe everyone has used right-click menus on the Web. Now I will share how to implement it. It is relatively simple.
Run the code:
window.onload = function() { document.oncontextmenu = block; document.body.onmouseup = function(event) { if (!event) event = window.event; if (event.button == 2) { var x = event.pageX || event.clientX; var y = event.pageY || event.clientY; document.getElementById("contextMenu").style.left = x "px"; document.getElementById("contextMenu").style.top = y "px"; document.getElementById("contextMenu").style.display = "block"; } } //阻止事件冒泡 document.getElementById("contextMenu").onclick = function(event) { event.stopPropagation(); } //点击其他地方隐藏 document.onclick = function() { document.getElementById("contextMenu").style.display = "none"; } for (var i = 0; i < getElementsByClassName("contextMenuItem").length; i ) { getElementsByClassName("contextMenuItem")[i].onclick = function(event) { event = event ? event : window.event var target = event.srcElement ? event.srcElement : event.targe; document.getElementById("contextMenu").style.display = "none"; //alert("您点击了: " target.innerHTML); } } } function block(event) { if (window.event) { event = window.event; event.returnValue = false; } else event.preventDefault(); } //兼容IE不支持getElementsByClassName function getElementsByClassName(className, root, tagName) { if (root) { root = typeof root == "string" ? document.getElementById(root) : root; } else { root = document.body; } tagName = tagName || "*"; if (document.getElementsByClassName) { return root.getElementsByClassName(className); } else { var tag = root.getElementsByTagName(tagName); var tagAll = []; for (var i = 0; i < tag.length; i ) { for (var j = 0, n = tag[i].className.split(' '); j < n.length; j ) { if (n[j] == className) { tagAll.push(tag[i]); break; } } } return tagAll; } }
Rendering:
The above is the entire content of this article, I hope you all like it.