D3(v7)入门二:D3操作DOM

2,179 阅读1分钟

D3全称Data-Driven DocumentsD3.js is a JavaScript library for manipulating documents based on data —— 官网。D3 是基于数据操作Dom的一个JS库。

选择器

d3选择器和jquery类似,可以通过类名(class)id标签属性等进行查找并返回selection

  • select([selector/node])
d3.select("body").slect("#name")
d3.select(".circle")
d3.select("#name")
  • selectAll([selector/nodes])
d3.selectAll("p")
d3.select("body").slectAll(".group")
  • slection.filter([selector/node])
d3.select("svg").filter("circle")
d3.selectAll("tr").filter(":nth-child(odd)");
  • selection.selectChild([selector/node])
d3.select("svg").selectChild("circle") // 选择第一个子元素
  • selection.selectChildren([selector/node])
d3.select("svg").selectChildren("circle") // 选择所有子元素

Dom操作

先来一个小例子,画三个圆。

const svg = d3.select("#root")
    .append("svg") // 添加一个svg
    .attr("width", 600)
    .attr("height", 600)
    .style("background", "gray");

const circles = [
    { text: 1, color: "red" },
    { text: 2, color: "green" },
    { text: 3, color: "blue" }
];

circles.forEach((c) => {
    svg.append("circle") // 添加一个圆
        .attr("class", "circle")
        .attr("id", `circle${c.text}`)
        .attr("cx", 50 * c.text)
        .attr("cy", 50)
        .attr("r", 20)
        .attr("fill", c.color);
});

image.png

新增

  • append(type) 添加到选择集后面
d3.select("svg").append("circle")
    .attr("cx", 50)
    .attr("cy", 50)
    .attr("r", 20);
  • insert(type[, before]) 添加到选择集与第一个bfore的前面
d3.select("svg").insert("rect", "circle");

image.png

如果 type 为字符串则为选择集中每个选中的插入一个指定类型(标签名)的元素,插入的位置为第一个匹配 before 选择条件的元素。

删除

  • remove 删除选择集
d3.select("rect").remove()

现在还没有方法,直接将删除的选择集,重新添加到文档中

总结

本章主要介绍了D3对dom元素(svg)的选择和操作,动态的添加和删除。实际开发中图表的绘制都是基于这些简单的api去实现了,所以需要尽力掌握。点击查看本章示例代码。