2016-03-05 58 views
0

我做了一个小小的h-bar示例。 我想要的是能够用鼠标调整任何栏的大小。 我通过关注 来选择一个我想在开始调整大小时开始调整大小,甚至通过鼠标移动事件来结束大小调整。 事实上,它的工作原理,但只适用于第一个酒吧,我没有看到酒吧调整大小,而我只是当我使鼠标,但只有当我amouse-up。 我在jsfiddle.net/Yves_49/jjj40cop/与D3.js中的酒吧交互

有一个小提琴这是我的代码

function draw_2() { 

var valueMax = 5; 
var tab_val = new Array(); 
for (currentLine = 0; currentLine < 10; currentLine++) { 
    var tab_temp = new Array(); 
    tab_temp['name'] = "name_" + currentLine; 
    tab_temp['value'] = Math.round(Math.random() * valueMax * 10)/10; 
    tab_val[currentLine] = tab_temp; 
    tab_temp.length = 0; 
} 

d3.select("body").selectAll("div.h-bar") 
    .data(tab_val) 
    .enter() 
    .append("div") 
    .attr("class", "h-bar") 
    .append("span"); 

d3.select("body").selectAll("div.h-bar") 
    .data(tab_val) 
    .attr("class", "h-bar") 
    .style("width", function(d) { 
     return (d.value * 100) + "px"; 
    }) 
    .style("background-color", function(d) { 
     return "rgb(" + (200 - Math.round(200 * d.value/valueMax)) + "," + (200 - Math.round(200 * d.value/valueMax)) + ",256)"; 
    }) 
    .select("span") 
    .text(function(d) { 
     return d.value; 
    }); 

d3.select("body").select(".h-bar") 
    .on("mouseover", function() { 
     d3.select(this) 
      .style("background-color", function() { 
       return "rgb(256,0,0)"; 
      }) 
    }) 
    .on("mouseout", function(d) { 
     d3.select(this) 
      .style("background-color", function(d) { 
       return "rgb(" + (200 - Math.round(200 * d.value/valueMax)) + "," + (200 - Math.round(200 * d.value/valueMax)) + ",256)"; 
      }) 
    }); 

d3.select("body") 
    .on("mouseup", function() { 
     d3.select(this) 
      .select(".h-bar") 
      .style("width", function() { 
       return (d3.mouse(this)[0]) + "px"; 
      }) 
      .style("background-color", function() { 
       return "rgb(0,256,0)"; 
      }) 
      .select("span") 
      .text(function(d) { 
       return (Math.round(d3.mouse(this)[0]/10)/10); 
      }); 
    }); 

伊夫

回答

2

这里的解决方案:http://jsfiddle.net/wtmsmwxk/1/

有几点我已经改正:

  • .select(".h-bar")只选择第一项,所以它解释了为什么只有你的第一个酒吧可以移动。您需要改用selectAll
  • 您需要在每个栏上注册mousedown事件,并在整个容器中注册mouseupmousemove事件,因为您应该假定鼠标可以移出栏。
  • 您需要记住哪个栏正在被拖动:在mousedown时间保留对该选择的引用。这是dragging变量的工作(如果没有发生拖动,我将其设置为undefined)。
  • 不断更新条的宽度,宽度更新函数应该在mousemove中,而不是mouseup。

主要新线:

var dragging = undefined; 
d3.select("body").selectAll(".h-bar") 
.on("mousedown", function() {dragging = d3.select(this)}); 

d3.select("body") 
.on("mouseup", function() {dragging=undefined}) 
.on("mousemove", function() { 
    if (!dragging) return; 
    dragging 
    .style("width", function() { ...}) 
}