欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

javascript實現(xiàn)在某個元素上阻止鼠標(biāo)右鍵事件的方法和實例

 更新時間:2014年08月12日 11:08:35   投稿:junjie  
這篇文章主要介紹了javascript實現(xiàn)在某個元素上阻止鼠標(biāo)右鍵事件的方法和實例,需要的朋友可以參考下

最近在做一個小東西的時候需要在某一個元素上“右擊”觸發(fā)一個自定義菜單,通過自定義的菜單對右擊的條目進行編輯。這就要求屏蔽默認(rèn)的右鍵菜單

IE和FF下面的元素都有oncontextmenu這個方法,在FF下面只要通過event.preventDefault()方法就可以輕松實現(xiàn)這個效果。IE并不支持這個方法,在IE下面一般是通過觸發(fā)方法后return false來實現(xiàn)阻止默認(rèn)事件的。

通常我們使用阻止右鍵事件是在全局阻止,即在document層面就將右鍵攔截,現(xiàn)在我想要實現(xiàn)的效果是只在特定的區(qū)域阻止默認(rèn)的右鍵事件,而其他區(qū)域并不影響。

通過實驗我發(fā)現(xiàn)要是在IE下綁定的方法中return false后在document層面上可以實現(xiàn)阻止右鍵的默認(rèn)行為。但是具體到某一個元素比如div,則失效。

最后通過查找手冊發(fā)現(xiàn),IE下的event對象有一個returnValue屬性,如果將這個屬性設(shè)置為false則不會觸發(fā)默認(rèn)的右鍵事件。類似如下:

復(fù)制代碼 代碼如下:

event.returnValue = false;

只要加入這句就實現(xiàn)了我想要的效果。完整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>在某個元素上阻止鼠標(biāo)右鍵默認(rèn)事件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+,F(xiàn)F,但是opera壓根就沒有oncontextmenu這個方法所以也就不能簡單的通過這個方法實現(xiàn),要想實現(xiàn)還需要通過其他的手段。

相關(guān)文章

最新評論