freeCodeCamp/curriculum/challenges/chinese/04-data-visualization/data-visualization-with-d3/change-styles-based-on-data...

3.0 KiB
Raw Blame History

id title challengeType videoUrl localeTitle
587d7fa7367417b2b2512bc7 Change Styles Based on Data 6 根据数据更改样式

Description

D3是关于数据的可视化和呈现。您可能希望根据数据更改元素的样式。您可以在style()方法中使用回调函数来更改不同元素的样式。例如如果值小于20您可能希望将数据点着色为蓝色否则为红色。您可以在style()方法中使用回调函数并包含条件逻辑。回调函数使用d参数表示数据点:
selection.style“color”d=> {
/ *根据条件返回颜色的逻辑* /
};
style()方法不仅限于设置color - 它也可以与其他CSS属性一起使用。

Instructions

style()方法添加到编辑器中的代码,以有条件地设置h2元素的color 。写回调函数如果数据值小于20则返回“red”否则返回“green”。 注意
您可以使用if-else逻辑或三元运算符。

Tests

tests:
  - text: 第一<code>h2</code>应该有一个<code>color</code>的红色。
    testString: assert($('h2').eq(0).css('color') == "rgb(255, 0, 0)");
  - text: 第二<code>h2</code>应该有一个<code>color</code>的绿色。
    testString: assert($('h2').eq(1).css('color') == "rgb(0, 128, 0)");
  - text: 第三<code>h2</code>应该有一个<code>color</code>的绿色。
    testString: assert($('h2').eq(2).css('color') == "rgb(0, 128, 0)");
  - text: 第四<code>h2</code>应该有一个<code>color</code>的红色。
    testString: assert($('h2').eq(3).css('color') == "rgb(255, 0, 0)");
  - text: 第五<code>h2</code>应该有一个<code>color</code>的绿色。
    testString: assert($('h2').eq(4).css('color') == "rgb(0, 128, 0)");
  - text: 第六<code>h2</code>应该有一个<code>color</code>的红色。
    testString: assert($('h2').eq(5).css('color') == "rgb(255, 0, 0)");
  - text: 第七<code>h2</code>应该有一个<code>color</code>的绿色。
    testString: assert($('h2').eq(6).css('color') == "rgb(0, 128, 0)");
  - text: 第八<code>h2</code>应该有一个<code>color</code>的红色。
    testString: assert($('h2').eq(7).css('color') == "rgb(255, 0, 0)");
  - text: 第九<code>h2</code>应该有一个<code>color</code>的红色。
    testString: assert($('h2').eq(8).css('color') == "rgb(255, 0, 0)");

Challenge Seed

<body>
  <script>
    const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];

    d3.select("body").selectAll("h2")
      .data(dataset)
      .enter()
      .append("h2")
      .text((d) => (d + " USD"))
      // Add your code below this line



      // Add your code above this line
  </script>
</body>

Solution

// solution required