按属性选择d3.js数据元素
Select d3.js data element by attribute
我有一个使用d3.js和svg表示的网格。我想做的是在单击瓷砖时更改瓷砖和所有相邻瓷砖的颜色。我想知道选择与单击的瓷砖相邻的瓷砖的最佳方式。到目前为止我的代码:
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);
}
我想知道的是,是否可以通过属性位置选择瓷砖/"矩形"?或者我是否应该考虑一种完全不同的方法?
您可以这样做(选择同一行中的所有矩形):
为了更好地理解算法,我对代码进行了注释。
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);
}
});
此处为工作代码。
相关文章:
- 基于数据元素限制动态表单字段
- 为什么DTM数据元素被调用两次
- 方法来使用jQuery选择匹配的数据元素
- 访问jQuery中的SVG数据元素
- Ajax 数据元素未拾取
- 从 json 字符串中提取数据元素
- Jquery验证插件,使用选项的数据元素作为验证检查
- 未捕获的异常:每个数据元素都必须实现一个唯一的“id”属性slick.dataview.js
- Knockout foreach 循环迭代相同的数据元素
- 从数据表重新加载 javascript 数据元素 asp.net 而不重新加载页面
- 如何从html中删除数据元素
- 使用jquery从HTML5数据元素中获取并执行函数+参数
- 按属性选择d3.js数据元素
- jQuery过滤器不返回数据元素,只返回整个对象
- 添加< >标记在选择的enter()部分的主数据元素之前
- 为数据元素设置一个变量
- 在javascript中转义数据元素中的撇号
- 如何访问CSV文件的数据元素
- 在adobedtm数据元素中寻找自定义脚本
- 问题更新Adobe分析变量通过数据元素在动态标签管理器- DTM