选择器的定义
和jQuery的选择器相似,D3.js的选择器也可以定位和操作HTML和SVG元素。
选择器的分类
d3.js默认提供两种选择器
1、单一选择器:d3.select()
可以用来选择第一个符合条件的元素。
示例:(将body的背景色设置为"#f60")
d3.select("body").style("background-color", "#f60");
2、多重选择器:d3.selectAll()
可以用来选择所有符合条件的元素。
示例:(将所有p标签中包含的内容颜色设置为"#08c")
d3.selectAll("p").style("color", "#08c");
选择器的特点
支持CSS选择器语法
以下示例(id、类名、属性)都可以使用:
d3.select("#id-name");
d3.select(".class-name");
d3.select("input[type=checkbox]");
链式调用
选择器返回的是一个选择集,支持链式操作。
根选择器
根选择器 .selection() 一般用于为选择器添加扩展方法。
const root = d3.selection();
添加一个方法的示例:
d3.selection.prototype.checked = function(value) {
return arguments.length < 1
? this.property("checked")
: this.property("checked", !!value);
};
添加后即可以直接使用:
// 将所有选中的checkbox取消选中
d3.selectAll("input[type=checkbox]").checked(false);
子选择器
选择子元素中的单个元素
选择所有p标签中的第一个b标签
const b = d3.selectAll("p").select("b");
也可以使用 .selectChild()
const b = d3.selectAll("p").selectChild("b");
.select() 中可以直接使用函数
// 选择所有p标签的相邻元素(上一个同辈元素)
const previous = d3.selectAll("p").select(function() {
return this.previousElementSibling;
});
选择子元素中的所有元素
// 选择所有p标签中的所有b标签
const b = d3.selectAll("p").selectAll("b");
也可以使用 .selectChildren()
// 选择所有p标签中的所有b标签
const b = d3.selectAll("p").selectChildren("b");
同样 .selectAll() 中可以直接使用函数
// 返回p标签的相邻元素(上一个和下一个同辈元素)
const sibling = d3.selectAll("p").selectAll(function() {
return [
this.previousElementSibling,
this.nextElementSibling
];
});
根据条件过滤所选元素
过滤出所有tr中的子元素中的偶数位元素(even表示偶数,odd表示奇数)
const even = d3.selectAll("tr").filter(":nth-child(even)");
上面的代码也可以写成,作用是相同的。
const even = d3.selectAll("tr:nth-child(even)");
使用函数
const even = d3.selectAll("tr").filter((d, i) => i & 1);
使用 .matcher() 过滤
const b = d3.selectAll(".class-name")
.filter(d3.matcher("div"));
等同于
const b = d3.selectAll(".class-name")
.filter("div");
感觉这里matcher的作用主要是让代码可读性更高.