gpt4 book ai didi

javascript - 使用下拉列表将样式添加到 D3 路径

转载 作者:行者123 更新时间:2023-11-30 16:23:42 24 4
gpt4 key购买 nike

我有一张正在构建的 D3 map 。我想用下拉菜单更改 map 。下拉列表将确定一个值,并且基于该值,绑定(bind)到 D3 map 的样式将发生变化。我怎样才能做到这一点?我试图尽可能地简化我的代码,但我不知道如何让它工作。在我的示例中,如果您从下拉列表中选择布朗克斯,它应该将整个 map 变成红色;否则它应该是蓝色的。

谢谢!

笨蛋:http://plnkr.co/edit/ouuArH6mgwvcckNZDa1L?p=preview

代码:

<!DOCTYPE html>
<meta charset="utf-8">

<style>
#boroughs {
stroke: #aaa;
stroke-width: 1px;
fill: #ccc;
width
}
</style>

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

<body>
<select id="filter">
<option>Select A Borough</option>
<option value="Bronx">Bronx</option>
<option value="Brooklyn">Brooklyn</option>
<option value="Manhattan">Manhattan</option>
<option value="Queens">Queens</option>
<option value="Staten_Island">Staten Island</option>
</select>

<script>
var selection;

d3.select('#filter')
.on("change", function () {
var section = document.getElementById("filter");
selection = section.options[section.selectedIndex].value;
});

console.log("selection:", selection);


var width = Math.max(960, window.innerWidth),
height = Math.max(500, window.innerHeight);

var container = d3.select("body").append("div")
.attr("id", "container")
.style("width", width + "px")
.style("height", height + "px");

d3.json("nyc.json", function(error, nyb) {

var projection = d3.geo.mercator()
.center([-73.94, 40.70])
.scale(50000)
.translate([(width) / 2, (height)/2]);

var path = d3.geo.path()
.projection(projection);

var map = container.append("svg")
.attr("id", "boroughs")
.style("width", width + "px")
.style("height", height + "px")
.selectAll(".state")
.data(nyb.features)
.enter().append("path")
.attr("class", function(d){ return d.properties.name; })
.attr("fill", function(d){
if (selection == "Bronx"){ return "#ff0000";}
else { return "#0000ff";}
})
.attr("d", path);

});

</script>
</body>
</html>

最佳答案

将类赋予路径,使其属于下拉框上的该类别:

var map = container.append("svg")
.attr("id", "boroughs")
.style("width", width + "px")
.style("height", height + "px")
.selectAll(".state")
.data(nyb.features)
.enter().append("path")
//this set the class
.attr("class", function(d){ return "state " + d.properties.borough.replace(" ", "_"); })

然后在选择上做:

d3.select('#filter')
.on("change", function () {

var section = document.getElementById("filter");

selection = section.options[section.selectedIndex].value;

d3.selectAll(".state").style("fill", "blue");//reset all to blue


d3.selectAll("."+selection.replace(" ", "_")).style("fill", "red"); //color the selected index
});

工作代码 here

希望这对您有所帮助!

关于javascript - 使用下拉列表将样式添加到 D3 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34390062/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com