javascript d3 和 svg 中的自定义上下文菜单

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

Custom context menu in d3 and svg

javascriptsvgcontextmenud3.jsright-click

提问by Christopher Chiche

I would like to have custom context menu appearing when I right click on an svg circle. For now I have found thisanswer that helps me to handle the right click with the following code:

当我右键单击 svg 圆圈时,我希望出现自定义上下文菜单。现在我找到了这个答案,它可以帮助我使用以下代码处理右键单击:

.on("contextmenu", function(data, index) {
   //handle right click

   //stop showing browser menu
   d3.event.preventDefault()
});

Now I would like to know how I can show a box containing some HTML.

现在我想知道如何显示一个包含一些 HTML 的框。

Thanks in advance.

提前致谢。

回答by meetamit

d3.select('#stock_details .sym').on("contextmenu", function(data, index) {
    var position = d3.mouse(this);
    d3.select('#my_custom_menu')
      .style('position', 'absolute')
      .style('left', position[0] + "px")
      .style('top', position[1] + "px")
      .style('display', 'block');

    d3.event.preventDefault();
});

回答by user

Just a comment on the accepted answer (don't have enough points to comment directly). But it seems like the newest version of d3 requires d3.event.pageX and d3.event.pageY instead of just x and y. Per the documentation here.

只是对接受的答案发表评论(没有足够的积分直接发表评论)。但似乎最新版本的 d3 需要 d3.event.pageX 和 d3.event.pageY 而不仅仅是 x 和 y。根据此处的文档。

So my code is (with some IE help from this site):

所以我的代码是(在这个网站上有一些 IE 帮助):

.on('contextmenu', function(data, index) {
      if (d3.event.pageX || d3.event.pageY) {
          var x = d3.event.pageX;
          var y = d3.event.pageY;
      } else if (d3.event.clientX || d3.event.clientY) {
          var x = d3.event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
          var y = d3.event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
      }

      d3.select('#action_div')
        .style('position', 'absolute')
        .style('left', x + 'px')
        .style('top', y + 'px')
        .style('display', 'block');

      d3.event.preventDefault();
  })