给 D3 标签添加样式 & 给 D3 元素添加悬停效果

472 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的21天,点击查看活动详情

给 D3 标签添加样式

介绍

D3 可以将样式添加到条形标签中。 fill 属性为 text 节点设置文本颜色, style() 方法设置其它样式的 CSS 规则,例如 font-familyfont-size

实操

text 元素的 font-size 设置为 25px,文本颜色设置为红色(red)。

  1. 所有标签的 fill 颜色应该是 red。
  2. 所有标签的 font-size 应为 25 像素。
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    const w = 500;
    const h = 100;

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

    svg.selectAll("rect")
       .data(dataset)
       .enter()
       .append("rect")
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - 3 * d)
       .attr("width", 25)
       .attr("height", (d, i) => d * 3)
       .attr("fill", "navy");

    svg.selectAll("text")
       .data(dataset)
       .enter()
       .append("text")
       .text((d) => d)
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - (3 * d) - 3)

       .attr("fill","red")
       .style("font-size","25px")

  </script>
</body>

给 D3 元素添加悬停效果

介绍

我们可以为用户的鼠标悬停行为添加高亮显示的效果。 到目前为止,矩形的样式应用了内置的 D3 和 SVG 方法,但是你也可以使用 CSS 来实现。

你可以使用 attr() 方法在 SVG 元素上设置 CSS class。 然后用 :hover 伪类为你新添加的 CSS 类设置鼠标悬停的效果。

实操

attr() 方法给所有的 rect 元素都添加 bar class。 当鼠标悬停在元素上时,它的 fill 将变为棕色。

  1. rect 元素应该有 bar class。
<style>
  .bar:hover {
    fill: brown;
  }
</style>
<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    const w = 500;
    const h = 100;

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

    svg.selectAll("rect")
       .data(dataset)
       .enter()
       .append("rect")
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - 3 * d)
       .attr("width", 25)
       .attr("height", (d, i) => 3 * d)
       .attr("fill", "navy")

       .attr("class","bar")

    svg.selectAll("text")
       .data(dataset)
       .enter()
       .append("text")
       .text((d) => d)
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - (3 * d) - 3);

  </script>
</body>