javascript实现在某个元素上阻止鼠标右键事件的方法和实例


最近在做一个小东西的时候需要在某一个元素上“右击”触发一个自定义菜单,通过自定义的菜单对右击的条目进行编辑。这就要求屏蔽默认的右键菜单

IE和FF下面的元素都有oncontextmenu这个方法,在FF下面只要通过event.preventDefault()方法就可以轻松实现这个效果。IE并不支持这个方法,在IE下面一般是通过触发方法后return false来实现阻止默认事件的。

通常我们使用阻止右键事件是在全局阻止,即在document层面就将右键拦截,现在我想要实现的效果是只在特定的区域阻止默认的右键事件,而其他区域并不影响。

通过实验我发现要是在IE下绑定的方法中return false后在document层面上可以实现阻止右键的默认行为。但是具体到某一个元素比如div,则失效。

最后通过查找手册发现,IE下的event对象有一个returnValue属性,如果将这个属性设置为false则不会触发默认的右键事件。类似如下:

复制代码 代码如下:

event.returnValue = false;

只要加入这句就实现了我想要的效果。完整Demo代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>在某个元素上阻止鼠标右键默认事件DEMO</title>
<style>
body{font-size:12px; line-height:24px; font-family:Arial, Helvetica, sans-serif;}
#activeArea{width:300px;height:200px; background:#06C; color:#fff;}
#cstCM{ width:120px; background:#eee; border:1px solid #ccc; position:absolute; }
#cstCM ul{margin:0; padding:0;}
#cstCM ul li{ list-style:none;padding:0 10px; cursor:default;}
#cstCM ul li:hover{ background:#009; color:#fff;}
.splitTop{ border-bottom:1px solid #ccc;}
.splitBottom{border-top:1px solid #fff;}
</style>
<script>
function customContextMenu(event){
	event.preventDefault ? event.preventDefault():(event.returnValue = false);
	var cstCM = document.getElementById('cstCM');
	cstCM.style.left = event.clientX + 'px';
	cstCM.style.top = event.clientY + 'px';
	cstCM.style.display = 'block';
	document.onmousedown = clearCustomCM;
}
function clearCustomCM(){
	document.getElementById('cstCM').style.display = 'none';
	document.onmousedown = null;
}
</script>
</head>

<body>
<div id="cstCM" style="display:none;">
	<ul>
		<li>View</li>
		<li>Sort By</li>
		<li class="splitTop">Refresh</li>
		<li class="splitBottom">Paste</li>
		<li class="splitTop">Paste Shortcut</li>
		<li class="splitBottom">Property</li>
	</ul>
</div>
<div id="activeArea" oncontextmenu = "customContextMenu(event)">
	Custom Context Menu Area
</div>
</body>
</html>

这个效果兼容IE6+,FF,但是opera压根就没有oncontextmenu这个方法所以也就不能简单的通过这个方法实现,要想实现还需要通过其他的手段。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3