javascript 为什么 AngularJS 中的 $event.preventDefault() 不会阻止上下文菜单出现?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23589900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 01:10:01  来源:igfitidea点击:

Why does $event.preventDefault() in AngularJS not prevent context menu from appearing?

javascriptangularjsevents

提问by Ben

Like the title says, I'm not sure why $event.preventDefault()is not preventing the context menu from appearing on right click.

正如标题所说,我不确定为什么$event.preventDefault()不阻止右键单击时出现上下文菜单。

I've written this simple examplein plunker to demonstrate the problem.

我在 plunker 中编写了这个简单的例子来演示这个问题。

Html:

网址:

<body ng-controller="MainCtrl">
    <div id="me" ng-mousedown="stopContext($event)">CLICK ME {{num}}</div>
</body>

Javascript:

Javascript:

  $scope.stopContext = function(ev) {
    $scope.num += 1;
    ev.preventDefault();
  };

Thanks in advance.

提前致谢。

回答by gkalpak

In order to prevent the context-menu you need to capture (and prevent) the contextmenuevent.

为了阻止上下文菜单,您需要捕获(并阻止)contextmenu事件。

Unfortunately, Angular does not have a directive for this event, so you'll have to create one yourself.

不幸的是,Angular 没有针对此事件的指令,因此您必须自己创建一个。

"Copying" from the source code of Angular (version 1.2.16):

从 Angular(版本 1.2.16)的源代码“复制”:

app.directive('myContextmenu', function ($parse) {
  return {
    compile: function (tElem, tAttrs) {
      var fn = $parse(tAttrs.myContextmenu);

      return function (scope, elem) {
        elem.on('contextmenu', onContextmenu);

        function onContextmenu(evt) {
          scope.$apply(function () {
            fn(scope, {$event: evt});
          });
        });
      };
    }
  };
});

Then, you can use it like this:

然后,您可以像这样使用它:

<div id="me" my-contextmenu="stopContext($event)">CLICK ME {{num}}</div>


See, also, this short demo.
Tested on latest version of Chrome, Firefox and Safari and found working.

另请参阅此简短演示
在最新版本的 Chrome、Firefox 和 Safari 上进行了测试,发现可以正常工作。