---
id: 587d7fa7367417b2b2512bc7
title: Change Styles Based on Data
required:
- src: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.3.0/d3.min.js'
challengeType: 6
videoUrl: ''
localeTitle: 根据数据更改样式
---
## Description
D3是关于数据的可视化和呈现。您可能希望根据数据更改元素的样式。您可以在style()
方法中使用回调函数来更改不同元素的样式。例如,如果值小于20,您可能希望将数据点着色为蓝色,否则为红色。您可以在style()
方法中使用回调函数并包含条件逻辑。回调函数使用d
参数表示数据点: selection.style(“color”,(d)=> {
/ *根据条件返回颜色的逻辑* /
});
style()
方法不仅限于设置color
- 它也可以与其他CSS属性一起使用。
## Instructions
将style()
方法添加到编辑器中的代码,以有条件地设置h2
元素的color
。写回调函数,如果数据值小于20,则返回“red”,否则返回“green”。 注意
您可以使用if-else逻辑或三元运算符。
## Tests
```yml
tests:
- text: 第一h2
应该有一个color
的红色。
testString: 'assert($("h2").eq(0).css("color") == "rgb(255, 0, 0)", "The first h2
should have a color
of red.");'
- text: 第二h2
应该有一个color
的绿色。
testString: 'assert($("h2").eq(1).css("color") == "rgb(0, 128, 0)", "The second h2
should have a color
of green.");'
- text: 第三h2
应该有一个color
的绿色。
testString: 'assert($("h2").eq(2).css("color") == "rgb(0, 128, 0)", "The third h2
should have a color
of green.");'
- text: 第四h2
应该有一个color
的红色。
testString: 'assert($("h2").eq(3).css("color") == "rgb(255, 0, 0)", "The fourth h2
should have a color
of red.");'
- text: 第五h2
应该有一个color
的绿色。
testString: 'assert($("h2").eq(4).css("color") == "rgb(0, 128, 0)", "The fifth h2
should have a color
of green.");'
- text: 第六h2
应该有一个color
的红色。
testString: 'assert($("h2").eq(5).css("color") == "rgb(255, 0, 0)", "The sixth h2
should have a color
of red.");'
- text: 第七h2
应该有一个color
的绿色。
testString: 'assert($("h2").eq(6).css("color") == "rgb(0, 128, 0)", "The seventh h2
should have a color
of green.");'
- text: 第八h2
应该有一个color
的红色。
testString: 'assert($("h2").eq(7).css("color") == "rgb(255, 0, 0)", "The eighth h2
should have a color
of red.");'
- text: 第九h2
应该有一个color
的红色。
testString: 'assert($("h2").eq(8).css("color") == "rgb(255, 0, 0)", "The ninth h2
should have a color
of red.");'
```
## Challenge Seed
## Solution
```js
// solution required
```