javascript实现在某个元素上阻止鼠标右键事件的方法和实例
最近在做一个小东西的时候需要在某一个元素上“右击”触发一个自定义菜单,通过自定义的菜单对右击的条目进行编辑。这就要求屏蔽默认的右键菜单
IE和FF下面的元素都有oncontextmenu这个方法,在FF下面只要通过event.preventDefault()方法就可以轻松实现这个效果。IE并不支持这个方法,在IE下面一般是通过触发方法后returnfalse来实现阻止默认事件的。
通常我们使用阻止右键事件是在全局阻止,即在document层面就将右键拦截,现在我想要实现的效果是只在特定的区域阻止默认的右键事件,而其他区域并不影响。
通过实验我发现要是在IE下绑定的方法中returnfalse后在document层面上可以实现阻止右键的默认行为。但是具体到某一个元素比如div,则失效。
最后通过查找手册发现,IE下的event对象有一个returnValue属性,如果将这个属性设置为false则不会触发默认的右键事件。类似如下:
event.returnValue=false;
只要加入这句就实现了我想要的效果。完整Demo代码:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <htmlxmlns="http://www.w3.org/1999/xhtml"> <head> <metahttp-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:1pxsolid#ccc;position:absolute;} #cstCMul{margin:0;padding:0;} #cstCMulli{list-style:none;padding:010px;cursor:default;} #cstCMulli:hover{background:#009;color:#fff;} .splitTop{border-bottom:1pxsolid#ccc;} .splitBottom{border-top:1pxsolid#fff;} </style> <script> functioncustomContextMenu(event){ event.preventDefault?event.preventDefault():(event.returnValue=false); varcstCM=document.getElementById('cstCM'); cstCM.style.left=event.clientX+'px'; cstCM.style.top=event.clientY+'px'; cstCM.style.display='block'; document.onmousedown=clearCustomCM; } functionclearCustomCM(){ document.getElementById('cstCM').style.display='none'; document.onmousedown=null; } </script> </head> <body> <divid="cstCM"style="display:none;"> <ul> <li>View</li> <li>SortBy</li> <liclass="splitTop">Refresh</li> <liclass="splitBottom">Paste</li> <liclass="splitTop">PasteShortcut</li> <liclass="splitBottom">Property</li> </ul> </div> <divid="activeArea"oncontextmenu="customContextMenu(event)"> CustomContextMenuArea </div> </body> </html>
这个效果兼容IE6+,FF,但是opera压根就没有oncontextmenu这个方法所以也就不能简单的通过这个方法实现,要想实现还需要通过其他的手段。