freeCodeCamp/curriculum/challenges/chinese-traditional/04-data-visualization/data-visualization-with-d3/add-a-hover-effect-to-a-d3-...

2.6 KiB

id title challengeType forumTopicId dashedName
587d7faa367417b2b2512bd4 給 D3 元素添加懸停效果 6 301469 add-a-hover-effect-to-a-d3-element

--description--

我們可以爲用戶的鼠標懸停行爲添加高亮顯示的效果。 到目前爲止,矩形的樣式應用了內置的 D3 和 SVG 方法,但是你也可以使用 CSS 來實現。

你可以使用 attr() 方法在 SVG 元素上設置 CSS class。 然後用 :hover 僞類爲你新添加的 CSS 類設置鼠標懸停的效果。

--instructions--

attr() 方法給所有的 rect 元素都添加 bar class。 當鼠標懸停在元素上時,它的 fill 將變爲棕色。

--hints--

rect 元素應該有 bar class。

assert($('rect').attr('class').trim().split(/\s+/g).includes('bar'));

--seed--

--seed-contents--

<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")
       // Add your code below this line



       // Add your code above this line

    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>

--solutions--

<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")
       // Add your code below this line
       .attr('class', 'bar')
       // Add your code above this line

    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>