Home>Article>Web Front-end> Javascript implements right-click mouse customization menu
JS屏蔽鼠标右键的两种方法,比较常用的一个JS小功能,用上这个代码后,浏览者在访问你网页的时候就不能点击右键了,点了也不会弹出右键菜单,本功能最好不要用的太多哦,有时候用户会反感的。
代码如下:
<html> <head> <title>屏蔽鼠标右键</title> </head> <body oncontextmenu=self.event.returnvalue=false> 第一种方法:在body标签里加上oncontextmenu=self.event.returnvalue=false; <br> <script language="javascript"> <!-- function document.oncontextmenu() { return false; } function nocontextmenu() { if(document.all) { event.cancelBubble=true; event.returnvalue=false; return false; } } --> </script> 第二种方法:在body里加入onmousedown="rclick()" oncontextmenu= "nocontextmenu()" <br> <script language="javascript"> <!-- function rclick() { if(document.all) { if (event.button == 2){ event.returnvalue=false; } } } --> </script> <br>详细情况请查看代码。<br> <br>现在点击你的鼠标右键,不起作用了。 </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助。
,两种JS实现屏蔽鼠标右键的方法,
"
在Web端,通常是不需要右键菜单,各个浏览器也有自己的右键菜单。但是对于一些特殊的网页,是需要右键菜单来增加用户体验的,比如百度音乐,QQ邮箱,相信大家都在Web端使用过右键菜单了,现在来分享一下如何实现,比较简单。
运行代码:
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; } }
效果图:
The above is the detailed content of Javascript implements right-click mouse customization menu. For more information, please follow other related articles on the PHP Chinese website!