简体   繁体   English

如何在d3.js树中添加带有contextmenu的全部展开按钮

[英]how to add expand all button with contextmenu to d3.js tree

var nodeEnter = node.enter().append("g")
.attr("class", "node")
.attr("transform", function (d) {
    return "translate(" + source.x0 + "," + source.y0 + ")";
 })
.on("click", click).on("contextmenu", function (data, index) {          
      d3.event.preventDefault();
       // add context menu...
     });;

You can see my code above. 您可以在上面看到我的代码。 I am new on d3.js and I couldn't find how to add an Expand All button on a context menu. 我是d3.js的新手,找不到在上下文菜单上添加“全部展开”按钮的方法。 Thanks for your helps.. PS: I mustn't use Jquery. 感谢您的帮助。.PS:我一定不能使用Jquery。

It's fairly easy to implement a context menu using D3. 使用D3实现上下文菜单是相当容易的。 First create a global variable for displaying the custom menu var contextDiv; 首先创建一个用于显示自定义菜单var contextDiv;的全局变量var contextDiv; . Then bind a click event to your svg element: 然后将click事件绑定到您的svg元素:

d3.select("svg").on("contextmenu", clickFunction);

And implement the function. 并实现功能。

function clickFunction() {
    event.preventDefault();

    contextDiv = d3.select("body").append("div")
        .style("position", "absolute")
        .style("top", event.pageY + 1 + "px")
        .style("left", event.pageX + 1 + "px");
    var contextTable = contextDiv.append("table")
        .style("border", "solid 1px");

    contextTable.append("tr")
        .append("td").text("Expand All").attr("id", "citem1");
    contextTable.append("tr")
        .append("td").text("Item2").attr("id", "citem2");
    contextTable.append("tr")
        .append("td").text("Item3").attr("id", "citem3");
    contextTable.on("click", tableClick);
}

Now implement the tableClick function. 现在实现tableClick函数。

function tableClick(){
    var target = d3.event.target.id;
    contextDiv.remove();

    if (target == "citem1")
        expand(root);
}

And finally the expandAll function. 最后是expandAll函数。 Note that root variable must be defined as the root of the tree. 注意,必须将root变量定义为树的根。 This is assuming you're basing your tree off This example. 这是假设你是立足你的树关闭一例。

function expand(d) {
    if (d._children) {
        d.children = d._children;
        d.children.forEach(expand);
        d._children = null;
    } else if (d.children) {
        d.children.forEach(expand);
    }
}

There is a lot more you'll have to do if you want your context menu to behave exactly like the inbuilt one, but this should be enough to get you started. 如果要使上下文菜单的行为与内置菜单完全一样,您还需要做很多事情,但这足以使您入门。 Also, here is a Fiddle with this behavior built in. 此外, 是内置了这种行为的小提琴。

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

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