标题 | 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代码: 03 <head> 04 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 05 <title>在某个元素上阻止鼠标右键默认事件DEMO</title> 06 <style> 07 body{font-size:12px; line-height:24px; font-family:Arial, Helvetica, sans-serif;} 08 #activeArea{width:300px;height:200px; background:#06C; color:#fff;} 09 #cstCM{ width:120px; background:#eee; border:1px solid #ccc; position:absolute; } 10 #cstCM ul{margin:0; padding:0;} 11 #cstCM ul li{ list-style:none;padding:0 10px; cursor:default;} 12 #cstCM ul li:hover{ background:#009; color:#fff;} 13 .splitTop{ border-bottom:1px solid #ccc;} 14 .splitBottom{border-top:1px solid #fff;} 15 </style> 16 <script> 17 function customContextMenu(event){ 18 event.preventDefault ? event.preventDefault():(event.returnValue = false); 19 var cstCM = document.getElementById('cstCM'); 20 cstCM.style.left = event.clientX + 'px'; 21 cstCM.style.top = event.clientY + 'px'; 22 cstCM.style.display = 'block'; 23 document.onmousedown = clearCustomCM; 24 } 25 function clearCustomCM(){ 26 document.getElementById('cstCM').style.display = 'none'; 27 document.onmousedown = null; 28 } 29 </script> 30 </head> 31 32 <body> 33 <div id="cstCM"> 34 <ul> 35 <li>View</li> 36 <li>Sort By</li> 37 <li>Refresh</li> 38 <li>Paste</li> 39 <li>Paste Shortcut</li> 40 <li>Property</li> 41 </ul> 42 </div> 43 <div id="activeArea" oncontextmenu = "customContextMenu(event)"> 44 Custom Context Menu Area 45 </div> 46 </body> 47 </html> 这个效果兼容IE6+,FF,但是opera压根就没有oncontextmenu这个方法所以也就不能简单的通过这个方法实现,要想实现还需要通过其他的手段。 |
随便看 |
|
在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。