您的位置:首页 > Web前端 > JavaScript

JavaScript禁用鼠标右键菜单

2011-09-15 00:00 537 查看
有些时候我们需要不让用户使用右键,比如不希望用户查看本页面源代码,或者复制本页的内容等等。当然用户可以用各种方法来达到目的,但是我们可以尽量增加他们达到这个目的的难度。使用以下js脚本就能够实现这个功能:


<script type="text/javascript">
// <![CDATA[
function doProhibit()
{
	if(window.Event) 
   		document.captureEvents(Event.MOUSEUP);
		
	function nocontextmenu() 
	{
   		event.cancelBubble = true 
   		event.returnvalue = false;
   		return false;
	}
	
	function norightclick(e) 
	{
   		if (window.Event)
   		{
      		if (e.which == 2 || e.which == 3)
      		return false;
   		}
   		else if (event.button == 2 || event.button == 3) 
   		{
			event.cancelBubble = true 
			event.returnvalue = false;
			return false;
   		}
	}
	document.oncontextmenu = nocontextmenu;  // for IE5+ 
	document.onmousedown = norightclick;  // 
}
// ]]>
</script>






// function doProhibit()
{
if(window.Event)
document.captureEvents(Event.MOUSEUP);

function nocontextmenu()
{
event.cancelBubble = true
event.returnvalue = false;
return false;
}

function norightclick(e)
{
if (window.Event)
{
if (e.which == 2 || e.which == 3)
return false;
}
else if (event.button == 2 || event.button == 3)
{
event.cancelBubble = true
event.returnvalue = false;
return false;
}
}
document.oncontextmenu = nocontextmenu; // for IE5+
document.onmousedown = norightclick; //
}
// ]]>


但是有些时候,输入框的右键不能屏蔽,那么可以使用下面脚本:


if (document.layers) 
{
	document.captureEvents(Event.MOUSEDOWN);
}
document.onmousedown = click;
document.oncontextmenu = new Function("return false;")
function click(e) 
{
  	e = e || event;
  	if (e.button == 2) 
	{
   		var tag = e.srcElement || e.target;
  		if (tag.type == "text" || tag.type == "textarea") 
    	{
        	document.oncontextmenu = new Function("return true;")
     	}
      	else 
      	{
     		document.oncontextmenu = new Function("return false;")
      	}
  	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: