D3 转换适用于 "background-color" 但不适用于 "width"
D3 transition working on "background-color" but not on "width"
简单问题:我正在尝试使用以下 d3.js 代码在 <div id="chart"></div
中编写动画条形图:
data=[100,200,400,350];
d3.select("#chart")
.selectAll("div")
.data(data)
.enter()
.append("div")
.style("height",30)
.style("width",function(d){return d/2})
.style("background-color","grey")
.transition()
.style("width",function(d){return d})
.style("background-color","blue");
结果很奇怪:条形颜色如预期的那样从 grey
变为 red
,但它们的宽度保持在 d/2
。
知道为什么吗?
您正在使用 css 样式设置宽度。这需要 units(px、em 或 %)。
更新代码:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id="chart"></div>
<script>
data = [100, 200, 400, 350];
d3.select("#chart")
.selectAll("div")
.data(data)
.enter()
.append("div")
.style("height", "30px")
.style("width", function(d) {
return d / 2 + "px"
})
.style("background-color", "grey")
.transition()
.duration(2000)
.style("width", function(d) {
return d + "px";
})
.style("background-color", "blue");
</script>
</body>
</html>
简单问题:我正在尝试使用以下 d3.js 代码在 <div id="chart"></div
中编写动画条形图:
data=[100,200,400,350];
d3.select("#chart")
.selectAll("div")
.data(data)
.enter()
.append("div")
.style("height",30)
.style("width",function(d){return d/2})
.style("background-color","grey")
.transition()
.style("width",function(d){return d})
.style("background-color","blue");
结果很奇怪:条形颜色如预期的那样从 grey
变为 red
,但它们的宽度保持在 d/2
。
知道为什么吗?
您正在使用 css 样式设置宽度。这需要 units(px、em 或 %)。
更新代码:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<div id="chart"></div>
<script>
data = [100, 200, 400, 350];
d3.select("#chart")
.selectAll("div")
.data(data)
.enter()
.append("div")
.style("height", "30px")
.style("width", function(d) {
return d / 2 + "px"
})
.style("background-color", "grey")
.transition()
.duration(2000)
.style("width", function(d) {
return d + "px";
})
.style("background-color", "blue");
</script>
</body>
</html>