简体   繁体   English

右键单击图像上的PreventDefault

[英]PreventDefault with right click on an image

Is it possible to fire document right click event on an image ? 是否可以在图像上触发文档右键单击事件?

That's what I've done so far, I can only track right click event on my Image 到目前为止,我就是这样做的,我只能在图片上跟踪右键事件

<script type="text/javascript">
    $("#myImage").mousedown(function (event) {
        if (event.which == 3) {
           //I need Some code to fire Document right click event (or maybe a different method)
        }
    });
</script>

Thanks for your help 谢谢你的帮助

Edit1: What I want exactly is when i right on click on my image, i want to show a menu , not the image right click menu, but the document right click menu It is like the image is not there or disabled, thanks again for your help :) Edit1:我想要的确切是当我右键单击图像时,我想要显示一个菜单 ,而不是图像右键单击菜单,而是文档右键单击菜单,就像图像不存在或已禁用一样,再次感谢你的帮助 :)

Edit2: What I did till now is disable right click event with preventDefault, now I need to display the menu: Edit2:到目前为止,我要做的是使用preventDefault禁用右键单击事件,现在我需要显示菜单:

<script type="text/javascript">
document.addEventListener('contextmenu', function (e) {
e.preventDefault();
//Need to display the menu
}, false);
</script>

Edit3: It worked thanks, I created my own menu, ofc it would have been great If I had the default menu but this one is perfect too :) Edit3:很好,谢谢,我创建了自己的菜单,如果我有默认菜单,但是这也是完美的,那当然很棒:)

<script type="text/javascript">
    $(document).bind("contextmenu", function (event) {
        event.preventDefault();
        $(".custom-menu").toggle(100).
  css({
      top: event.pageY + "px",
      left: event.pageX + "px"
  });
    });
   //To hide the menu if left click event is fired
    $(document).bind("mousedown", function () {
        $(".custom-menu").hide(100);
    });
</script>
//New Menu
<ul class='custom-menu'>
  <a>Back</a><br />
  <a>Refresh</a><br />
  <a>Save</a><br />
</ul>
<style type="text/css">
.custom-menu {
  position: absolute;
  background-color:#EEE;
  overflow: hidden;
  width: 100px;
  }
</style>

event.which is actually the wrong thing to check... event.which实际上是错误的检查...

Use event.button == 2 . 使用event.button == 2 See the MouseEvent documentation. 请参阅MouseEvent文档。

Or use contextmenu event , as @MarshallOfSound suggested (but subsequently removed as an answer), but be aware that it might also fire if the user invoked the contextmenu by another method than right-clicking, eg left-click + CTRL on OSX. 或使用contextmenu event ,如@MarshallOfSound所建议的(但随后作为答案删除),但要注意,如果用户通过右键单击(例如,在OSX上单击+ CTRL以外的其他方法来调用contextmenu ,则它也可能触发。 And it is pretty recent HTML5 stuff, so it might not work with older browsers. 而且这是最近的HTML5内容,因此它可能不适用于较旧的浏览器。

Edit After your edit it appears contextmenu might be better suited for your needs. 编辑编辑后,将显示contextmenu 菜单可能更适合您的需求。 Also, event.preventDefault is your friend. 另外, event.preventDefault是您的朋友。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM