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
Use both "d3.event.preventDefault" and "d3.event.which"
提问by Agata
This code works perfect — except in Internet Explorer 11.
The deleteNode(d)
only calls if the mousedown
handle 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 contextmenu
and mousedown
events?
如何修复不显示上下文菜单或同时捕获contextmenu
和mousedown
事件?
回答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 d
refers to the datum bound to the node, not to the node itself. Within the event listener this
will 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>