D3.js 如何在添加放大和缩小功能的同时停止svg跳转

D3.js 如何在添加放大和缩小功能的同时停止svg跳转,d3.js,svg,tree,D3.js,Svg,Tree,您好,我刚刚为D3 tree.js添加了缩放功能,但在拖动svg时,它会上下跳动,有人能帮我吗?一切正常,但只拖动gable svg不工作,我尝试了谷歌提供的几个附加g的解决方案,但问题仍然没有解决。有人能帮我吗 .工具提示{ 位置:绝对位置; 文本对齐:左对齐; 空白:正常; 填充:4px; 字体大小:14px; 背景:谭; 边框:1px纯色灰色; } .节点圆{ 填充:#fff; 笔画:钢蓝; 笔画宽度:3px; } .节点文本{ 字体:12px无衬线; } .链接{ 填充:无; 冲程

您好,我刚刚为D3 tree.js添加了缩放功能,但在拖动svg时,它会上下跳动,有人能帮我吗?一切正常,但只拖动gable svg不工作,我尝试了谷歌提供的几个附加g的解决方案,但问题仍然没有解决。有人能帮我吗


.工具提示{
位置:绝对位置;
文本对齐:左对齐;
空白:正常;
填充:4px;
字体大小:14px;
背景:谭;
边框:1px纯色灰色;
}
.节点圆{
填充:#fff;
笔画:钢蓝;
笔画宽度:3px;
}
.节点文本{
字体:12px无衬线;
}
.链接{
填充:无;
冲程:#ccc;
笔画宽度:2px;
}
.d3关联菜单{
位置:绝对位置;
显示:无;
背景色:#F2F2;
边界半径:4px;
字体系列:Arial,无衬线;
字体大小:14px;
最小宽度:150px;
边框:1px实心#d4;
z指数:1200;
}
.d3上下文菜单{
列表样式类型:无;
利润率:4px0px;
填充:0px;
游标:默认值;
}
.d3上下文菜单ul li{
填充:4px16px;
}
.d3上下文菜单ul li:悬停{
背景色:#4677f8;
颜色:#fefefe;
}
函数工具提示(){
返回d3.选择(“正文”).追加(“div”)
.attr(“类”、“工具提示”)
.style(“不透明度”,0);}
d3.contextMenu=函数(菜单,openCallback){
//创建将保存上下文菜单的div元素
d3.选择全部('.d3上下文菜单')。数据([1])
.输入()
.append('div'))
.attr('class','d3上下文菜单');
//关闭菜单
d3.选择('div')。打开('click.d3上下文菜单',函数(){
d3.选择('.d3上下文菜单').style('display','none');
});
//当contextmenu事件发生时执行此操作
返回函数(){
让elm=这个;
d3.选择全部('.d3上下文菜单').html('');
let list=d3。选择全部('.d3上下文菜单')。追加('ul');
列表。选择全部('li')。数据(菜单)。输入()
.append('li')
.html(函数(d){
返回d.title;
})
.on('click',函数(d,i){
d、 行动(elm、数据、索引);
d3.选择('.d3上下文菜单').style('display','none');
});
//openCallback允许在显示菜单之前触发操作
//例如,关闭工具提示
if(openCallback)openCallback(数据、索引);
//显示关联菜单
d3.选择(“.d3上下文菜单”)
.style('left',(d3.event.pageX-2)+'px')
.style('top',(d3.event.pageY-2)+'px')
.style(“显示”、“块”);
d3.event.preventDefault();
};
};
变量菜单=[
{
标题:“URL”,
行动:功能(elm、d、i){
console.log('Item#1 clicked!'+d);
console.log('此圆圈的数据为:'+d);
}
},
{
标题:“探索”,
行动:功能(elm、d、i){
控制台日志(d);
console.log('此圆圈的数据为:'+d);
}
}
]
var数据=[1,2,3];
选择的var=null;
树形变种=
{
“名称”:“顶级”,
“儿童”:[
{ 
“名称”:“2级:A”,
“儿童”:[
{“姓名”:“儿子”},
{“姓名”:“A的女儿”}
]
},
{“名称”:“级别2:B”}
]
};
//预定义的框大小
设rectNode={
宽度:120,
身高:17,
文本边距:5
};
//设置图表的尺寸和边距
var margin={顶部:20,右侧:90,底部:30,左侧:90},
宽度=960-margin.left-margin.right,
高度=500-margin.top-margin.bottom;
//将svg对象附加到页面主体
//将“组”元素附加到“svg”
//将“组”元素移动到左上角
var svg=d3.选择(“div”)
.append(“svg”)
.attr(“宽度”,宽度+边距。右侧+边距。左侧)
.attr(“高度”,高度+边距。顶部+边距。底部);
调用(d3.zoom().on(“zoom”,function(){svg.attr(“transform”,d3.event.transform)});
svg.append(“g”)
.attr(“转换”、“转换”
+margin.left+”,“+margin.top+”)
;
var i=0,
持续时间=750,
根;
//声明树布局并指定大小
var treemap=d3.tree().size([height,width]);
//指定父对象、子对象、高度和深度
root=d3.hierarchy(treeData,函数(d){返回d.children;});
root.x0=高度/2;
root.y0=0;
//在第二层之后崩溃
根。子。forEach(塌陷);
更新(根);
//折叠节点及其所有子节点
功能崩溃(d){
如果(d.儿童){
d、 _children=d.children
d、 _儿童。forEach(崩溃)
d、 children=null
}
}
函数更新(源){
//为节点指定x和y位置
var treeData=树映射(根);
//计算新的树布局。
var nodes=treeData.subjects(),
links=treeData.subjects().slice(1);
//为固定深度进行规格化。
forEach(函数(d){d.y=d.depth*180});
//*******************节点部分***************************
//更新节点。。。
var node=svg.selectAll('g.node')
.data(节点,函数(d){返回d.id | |(d.id=++i)});
//在父对象的上一个位置输入任何新模式。
var nodeEnter=node.enter().append('g')
.attr('类','节点')
.attr(“转换”,函数(d){
返回“translate”(“+source.y0+”,“+source.x0+”);
});
//.on('点击',点击);
//为节点添加圆
nodeEnter.append('circle'))
.attr('类','节点')
.attr('r',0)
.样式(“填充”,功能(d){
返回d.#儿童?“淡蓝色”:“fff”;
});
设rectGrpEnter=nodeEnte
<!DOCTYPE html>
<meta charset="UTF-8">
<style>
.tooltip {  
    position: absolute;         
    text-align: left;           
      white-space: normal;                  
    padding: 4px;               
    font-size: 14px;        
    background: tan;    
    border: 1px solid gray;     
}

.node circle {
  fill: #fff;
  stroke: steelblue;
  stroke-width: 3px;
}

.node text {
  font: 12px sans-serif;
}

.link {
  fill: none;
  stroke: #ccc;
  stroke-width: 2px;
}
.d3-context-menu {
    position: absolute;
    display: none;
    background-color: #f2f2f2;
    border-radius: 4px;

    font-family: Arial, sans-serif;
    font-size: 14px;
    min-width: 150px;
    border: 1px solid #d4d4d4;

    z-index:1200;
}

.d3-context-menu ul {
    list-style-type: none;
    margin: 4px 0px;
    padding: 0px;
    cursor: default;
}

.d3-context-menu ul li {
    padding: 4px 16px;
}

.d3-context-menu ul li:hover {
    background-color: #4677f8;
    color: #fefefe;
}
</style>

<body>
<div></div>
<!-- load the d3.js library --> 
<script src="https://d3js.org/d3.v4.min.js"></script>
<script >
function tooltip(){
return d3.select("body").append("div")  
    .attr("class", "tooltip")               
    .style("opacity", 0);}


d3.contextMenu = function (menu, openCallback) {

    // create the div element that will hold the context menu
    d3.selectAll('.d3-context-menu').data([1])
        .enter()
        .append('div')
        .attr('class', 'd3-context-menu');

    // close menu
    d3.select('div').on('click.d3-context-menu', function() {
        d3.select('.d3-context-menu').style('display', 'none');
    });

    // this gets executed when a contextmenu event occurs
    return function() { 
        let elm = this;

        d3.selectAll('.d3-context-menu').html('');
        let list = d3.selectAll('.d3-context-menu').append('ul');
        list.selectAll('li').data(menu).enter()
            .append('li')
            .html(function(d) {
                return d.title;
            })
            .on('click', function(d, i) {
                d.action(elm, data, index);
                d3.select('.d3-context-menu').style('display', 'none');
            });

        // the openCallback allows an action to fire before the menu is displayed
        // an example usage would be closing a tooltip
        if (openCallback) openCallback(data, index);

        // display context menu
        d3.select('.d3-context-menu')
            .style('left', (d3.event.pageX - 2) + 'px')
            .style('top', (d3.event.pageY - 2) + 'px')
            .style('display', 'block');

        d3.event.preventDefault();
    };
};</script>
<script>
var menu = [
            {
                title: 'URL',
                action: function(elm, d, i) {
                    console.log('Item #1 clicked!'+d);
                    console.log('The data for this circle is: ' + d);
                }
            },
            {
                title: 'ExPLORE',
                action: function(elm, d, i) {
                    console.log(d);
                    console.log('The data for this circle is: ' + d);
                }
            }
        ]

        var data = [1, 2, 3];
var selected=null;
var treeData =
  {
    "name": "Top Level",
    "children": [
      { 
        "name": "Level 2: A",
        "children": [
          { "name": "Son of A" },
          { "name": "Daughter of A" }
        ]
      },
      { "name": "Level 2: B" }
    ]
  };
//Predefined Box Size 
  let rectNode = {
  width: 120,
  height: 17,
  textMargin: 5
  };
// Set the dimensions and margins of the diagram
var margin = {top: 20, right: 90, bottom: 30, left: 90},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// append the svg object to the body of the page
// appends a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("div")

.append("svg")
    .attr("width", width + margin.right + margin.left)
    .attr("height", height + margin.top + margin.bottom);

  svg.call(d3.zoom().on("zoom", function () { svg.attr("transform", d3.event.transform) }));
svg.append("g")
    .attr("transform", "translate("
          + margin.left + "," + margin.top + ")")
  ;
var i = 0,
    duration = 750,
    root;

// declares a tree layout and assigns the size
var treemap = d3.tree().size([height, width]);

// Assigns parent, children, height, depth
root = d3.hierarchy(treeData, function(d) { return d.children; });
root.x0 = height / 2;
root.y0 = 0;

// Collapse after the second level
root.children.forEach(collapse);

update(root);

// Collapse the node and all it's children
function collapse(d) {
  if(d.children) {
    d._children = d.children
    d._children.forEach(collapse)
    d.children = null
  }
}

function update(source) {

  // Assigns the x and y position for the nodes
  var treeData = treemap(root);

  // Compute the new tree layout.
  var nodes = treeData.descendants(),
      links = treeData.descendants().slice(1);

  // Normalize for fixed-depth.
  nodes.forEach(function(d){ d.y = d.depth * 180});

  // ****************** Nodes section ***************************

  // Update the nodes...
  var node = svg.selectAll('g.node')
      .data(nodes, function(d) {return d.id || (d.id = ++i); });

  // Enter any new modes at the parent's previous position.
  var nodeEnter = node.enter().append('g')
      .attr('class', 'node')
      .attr("transform", function(d) {
        return "translate(" + source.y0 + "," + source.x0 + ")";
    });
    //.on('click', click);

  // Add Circle for the nodes
  nodeEnter.append('circle')
      .attr('class', 'node')
      .attr('r', 0)
      .style("fill", function(d) {
          return d._children ? "lightsteelblue" : "#fff";
      });
let rectGrpEnter = nodeEnter.append('g')
  .attr('class', 'node-rect-text-grp');
  rectGrpEnter.append('rect')
  .attr('rx', 6)
  .attr('ry', 6)
  .attr('x',-20)
  .attr('y',-20)
  .style('fill', "#337ab7")
  .attr('width',  50)
  .attr('height',50)
  .on('contextmenu', d3.contextMenu(menu));
  // Add labels for the nodes
  nodeEnter.append('text')
      .attr("dy", ".35em")
      .attr("x", function(d) {
          return d.children || d._children ? -13 : 13;
      })
      .attr("text-anchor", function(d) {
          return d.children || d._children ? "end" : "start";
      })
      .text(function(d) { return d.data.name; });

  // UPDATE
  var nodeUpdate = nodeEnter.merge(node);

  // Transition to the proper position for the node
  nodeUpdate.transition()
    .duration(duration)
    .attr("transform", function(d) { 
        return "translate(" + d.y + "," + d.x + ")";
     });

  // Update the node attributes and style
  nodeUpdate.select('circle.node')
    .attr('r', 10)
    .style("fill", function(d) {
        return d._children ? "lightsteelblue" : "#fff";
    })

    .attr('cursor', 'pointer');


  // Remove any exiting nodes
  var nodeExit = node.exit().transition()
      .duration(duration)
      .attr("transform", function(d) {
          return "translate(" + source.y + "," + source.x + ")";
      })
      .remove();

  // On exit reduce the node circles size to 0
  nodeExit.select('circle')
    .attr('r', 1e-6);

  // On exit reduce the opacity of text labels
  nodeExit.select('text')
    .style('fill-opacity', 1e-6);

  // ****************** links section ***************************

  // Update the links...
  var link = svg.selectAll('path.link')
      .data(links, function(d) { return d.id; });

  // Enter any new links at the parent's previous position.
  var linkEnter = link.enter().insert('path', "g")
      .attr("class", "link")
      .attr('d', function(d){
        var o = {x: source.x0, y: source.y0}
        return diagonal(o, o)
      });

  // UPDATE
  var linkUpdate = linkEnter.merge(link);

  // Transition back to the parent element position
  linkUpdate.transition()
      .duration(duration)
      .attr('d', function(d){ return diagonal(d, d.parent) });

  // Remove any exiting links
  var linkExit = link.exit().transition()
      .duration(duration)
      .attr('d', function(d) {
        var o = {x: source.x, y: source.y}
        return diagonal(o, o)
      })
      .remove();

  // Store the old positions for transition.
  nodes.forEach(function(d){
    d.x0 = d.x;
    d.y0 = d.y;
  });

  // Creates a curved (diagonal) path from parent to the child nodes
  function diagonal(s, d) {

    path = `M ${s.y} ${s.x}
            C ${(s.y + d.y) / 2} ${s.x},
              ${(s.y + d.y) / 2} ${d.x},
              ${d.y} ${d.x}`

    return path
  }

  // Toggle children on click.
  function click(d) {
    if (d.children) {
        d._children = d.children;
        d.children = null;
      } else {
        d.children = d._children;
        d._children = null;
      }
    update(d);
  }

  function contextmenu(d){
  if(d.children){
  alert("Has Children")
  }
  else{
  alert("NO Has Children")
  selected = d;
   update(d);


   var myObj, i, x = "";
myObj = {
  "name":"John",
  "age":30,
  "cars":[  {name: "child1"}, { name: "child2"},  {name: "child3"}]
};

for (i in myObj.cars) {
   var newNodeObj =myObj.cars[i];
   ;
   //Creates new Node
   var newNode = d3.hierarchy(newNodeObj);
   newNode.depth = selected.depth + 1;
   newNode.height = selected.height - 1;
   newNode.parent = selected;

   if(!selected.children){
     selected.children = [];
         selected.data.children = [];
   }
   selected.children.push(newNode);
  }
  update(selected);
  }
  }
}

</script>
</body>