Files
freeCodeCamp/curriculum/challenges/chinese/04-data-visualization/data-visualization-with-d3/add-classes-with-d3.md
Nicholas Carrigan (he/him) aff0ea700d chore(i8n,learn): processed translations (#41350)
* chore(i8n,learn): processed translations

* fix: restore deleted test

* fix: revert casing change

Co-authored-by: Crowdin Bot <support+bot@crowdin.com>
2021-03-04 10:49:46 -07:00

92 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
id: 587d7fa7367417b2b2512bc8
title: 用 D3 添加 Class
challengeType: 6
forumTopicId: 301473
dashedName: add-classes-with-d3
---
# --description--
即使对小型 app 来说,在 HTML 元素中大量使用内联样式也十分难以管理。 给元素添加类,并使用 CSS 规则给类添加样式会更加方便。 D3 中的 `attr()` 方法可以给元素添加任何 HTML 属性,包括 class 名称。
`attr()` 方法和 `style()` 的使用方法一样。 它使用逗号分隔值,并且可以使用回调函数。 这里是一个给选中元素添加 class 名为 "container" 的例子:
`selection.attr("class", "container");`
请注意当你需要添加类时“class" 参数不会发生改变,只有 "container" 参数会发生变化。
# --instructions--
`attr()` 方法添加到编辑器的代码中,并在 `div` 元素上添加一个 `bar` 类。
# --hints--
`div` 元素应该有值为 `bar` 的类。
```js
assert($('div').attr('class') == 'bar');
```
你应该使用 `attr()` 方法。
```js
assert(code.match(/\.attr/g));
```
# --seed--
## --seed-contents--
```html
<style>
.bar {
width: 25px;
height: 100px;
display: inline-block;
background-color: blue;
}
</style>
<body>
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("div")
.data(dataset)
.enter()
.append("div")
// Add your code below this line
// Add your code above this line
</script>
</body>
```
# --solutions--
```html
<style>
.bar {
width: 25px;
height: 100px;
display: inline-block;
background-color: blue;
}
</style>
<body>
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("div")
.data(dataset)
.enter()
.append("div")
// Add your code below this line
.attr("class","bar");
// Add your code above this line
</script>
</body>
```