javascript - 按属性选择 d3.js 数据元素

标签 javascript d3.js svg

我有一个使用 d3.js 和 svg 表示的网格。 我想要做的是在单击图 block 时更改图 block 和所有相邻图 block 的颜色。 我想知道选择与单击的图 block 相邻的图 block 的最佳方法。 到目前为止我的代码:

var w = 960,
    h = 500,
    z = 20,
    x = w / z,
    y = h / z;

var svg = d3.select("body").append("svg")
    .attr("width", w)
    .attr("height", h);

svg.selectAll("rect")
    .data(d3.range(x * y))
  .enter().append("rect")
    .attr("transform", translate)
    .attr("position", pos)
    .attr("width", z)
    .attr("height", z)
    .attr("clicked", false)
    //.on("mouseover", mouseover)
    .on("click", click)
    .style("stroke", "rgb(6,120,155)")
    .style("stroke-width", 2);
    .style("fill", "rgb(255, 255, 255)")


function translate(d) {
  return "translate(" + (d % x) * z + "," + Math.floor(d / x) * z + ")";
}

function pos(d) {
  return [ (d % x) * z , Math.floor(d / x) * z ];
}

function click(d) {
  var currentColor = this.style.fill;
  var clickedYet = d3.select(this).attr("clicked");
  currentColor = currentColor == "rgb(255, 255, 255)" ? "rgb(255, 0, 255)" : "rgb(255, 255, 255)";


  d3.select(this)
    .attr("clicked", true)
    .transition()
      .style("fill", currentColor);

}

我想知道的是,是否可以通过属性位置选择tiles/“rect”?或者我是否应该考虑一种完全不同的方法?

最佳答案

你可以这样做(选择同一行中的所有矩形):

我对代码进行了注释,以便更好地理解算法。

function click(d) {
  var currentColor = this.style.fill;
  //this will give the data associated with the rectangle
  var clickeddata = d3.select(this).data();
 //this will give the row to be highlihted
  var row = parseInt(clickeddata/x);
  //current color calculation
  currentColor = currentColor == "rgb(255, 255, 255)" ? "rgb(255, 0, 255)" : "rgb(255, 255, 255)";
  //iterate through all the rectangle
  d3.selectAll("rect")[0].forEach(function(r){
    //all rectangle with same row 
    if(parseInt(d3.select(r).data()/x) == row){
      //make it color as it is in the same row
      d3.select(r)
        .attr("clicked", true)
        .transition()
          .style("fill", currentColor);     
    }
  });

工作代码here .

关于javascript - 按属性选择 d3.js 数据元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34502992/

相关文章:

javascript - ng-option 过滤器不工作

javascript - D3 如何从不透明刻度中去除刻度点

JavaScript D3 : zoom

javascript - 在日期上添加矩形 D3

html - 如果从 svg 中省略,viewBox 属性的默认值是多少?

javascript - jquery datatable - 通过单击表页脚单元格获取列名称

javascript - Socket.io - 变量未在 socket.on 外部更新

html - d3 v4 内部填充设置为 .001 实际上不会导致范围之间的小填充

css - SVG 动画 - 来自中心的 SVG 的 CSS 悬停动画

javascript - 算上一个月