title: 【D3.js】1.20-给 D3 元素添加工具提示
 date: 2022-12-02 15:04
 tags: [JavaScript,CSS,HTML,D3.js,SVG]
继续增强交互性:给元素添加悬停提示。
一、学习目标
- 如何给元素添加悬停提示?
通过title元素:增加title元素,通过.text()设置title的值
二、题目
在每个 rect 节点下附加 title 元素。 然后用回调函数调用 text() 方法使它的文本显示数据值。

三、通关代码
<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) => d * 3)
       .attr("fill", "navy")
       .attr("class", "bar")
       // 在这行下面添加代码
        .append("title")
        .text((d,i)=>d)
       // 在这行上面添加代码
    svg.selectAll("text")
       .data(dataset)
       .enter()
       .append("text")
       .text((d) => d)
       .attr("x", (d, i) => i * 30)
       .attr("y", (d, i) => h - (d * 3 + 3))
  </script>
</body>
参考
- 用 D3 实现数据可视化: 给 D3 元素添加工具提示 | freeCodeCamp.org
更新
前往【D3.js】1.20-给 D3 元素添加工具提示 | 张鹏帅的官方网站查看更新。







![[附源码]计算机毕业设计JAVA校园一卡通管理信息系统台](https://img-blog.csdnimg.cn/384ff0cde90d4aaa93ddb06d9c140644.png)










![[附源码]计算机毕业设计springboot校园商铺](https://img-blog.csdnimg.cn/80f868d4a3a346158e29165ac1ef8984.png)
![[附源码]Python计算机毕业设计Django基于web的羽毛球管理系统](https://img-blog.csdnimg.cn/162d3968520145bd9d5d26d0fbb8319a.png)