与D3.js中的条形交互

时间:2016-03-05 11:38:53

标签: d3.js

我做了一个小小的h-bar示例。 我想要的是能够用鼠标调整任何栏的大小。 我专注于选择一个 当我创建鼠标按下并通过鼠标按下事件结束调整大小时,我想开始调整大小。 实际上,它的工作原理只适用于第一个酒吧而且我没有看到酒吧调整大小,而我只是在做鼠标时才会调整大小。 我在jsfiddle.net/Yves_49/jjj40cop/

有一个小提琴

这是我的代码

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);
            });
    });

伊夫

1 个答案:

答案 0 :(得分: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() { ...})
 }