javascript 使用“d3.event.preventDefault”和“d3.event.which”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30170944/
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 11:50:45  来源:igfitidea点击:

Use both "d3.event.preventDefault" and "d3.event.which"

javascriptd3.js

提问by Agata

This code works perfect — except in Internet Explorer 11. The deleteNode(d)only calls if the mousedownhandle is commented out.

这段代码完美运行——除了在Internet Explorer 11 中。该deleteNode(d)如果仅调用mousedown句柄注释掉。

circle.enter().append('circle')
  .on('contextmenu', function (d) {
    deleteNode(d);
  })
  .on('mousedown', function (d) {
    setNode(d);
  });

That's why I try to catch right click with mousedown, but the context menu still appears.

这就是为什么我尝试用 捕捉右键单击mousedown,但上下文菜单仍然出现。

circle.enter().append('circle')
  .on('mousedown', function (d) {
    d3.event.preventDefault();
    if (d3.event.which == 3) {
      deleteNode(d);
    }
    setNode(d);
  });

How to fix not showing up the context menu or catching both contextmenuand mousedownevents?

如何修复不显示上下文菜单或同时捕获contextmenumousedown事件?

回答by altocumulus

You are close to your own solution to the problem. All that is needed is already there, you just need to rearrange it a bit:

你已经接近你自己的问题解决方案了。所需的一切都已经存在,你只需要重新排列一下:

circle.enter().append("circle")
    .on("contextmenu", function(d) {
        d3.event.preventDefault();
    })
    .on("mousedown", function (d) {
        if (d3.event.which == 3) {
            deleteNode(d);  // <-- d probably needs to be replaced
        } else {
            setNode(d);    // <-- d probably needs to be replaced
        }
    });

This works for me in IE11 as well as in FF and Chrome.

这对我在 IE11 以及 FF 和 Chrome 中都有效。

As an aside, please note that drefers to the datum bound to the node, not to the node itself. Within the event listener thiswill refer to the current node.

顺便说一句,请注意,d指的是绑定到节点的数据,而不是节点本身。在事件侦听器内this将引用当前节点。

var svg = d3.select("svg");                
svg.append("circle")
    .attr({
        "cx": 100,
        "cy": 100,
        "r": 100
    })
    .on("contextmenu", function(e) {
        d3.event.preventDefault();
    })
    .on("mousedown", function (e) {
        if (d3.event.which == 3) {
          //console.log("deleteNode(d)");
        } else {
          //console.log("setNode(d)");
        }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<svg width="400" height="400">
</svg>