我在 d3.js 中有一张简单的纽约市行政区 map 。我想添加指向每个行政区的链接,但我不知道该怎么做。
下面是我现在拥有的代码——只有一个指向纽约时报网站的占位符链接。但是,它添加了 <a href>
在<path>
里面标签,这不起作用。如何附加链接?这可能吗?
谢谢!
<!DOCTYPE html>
<meta charset="utf-8">
<style>
#boroughs {
stroke: none;
stroke-width: 0px;
fill: #ddd;
opacity:.7;
position:absolute;
top:0;
left:0;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<body>
<script>
// map
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");
var projection = d3.geo.mercator()
.center([-73.94, 40.70])
.scale(80000)
.translate([(width) / 2, (height)/2]);
var path = d3.geo.path()
.projection(projection);
d3.json("nyc.json", function(error, nyb) {
var map = container.append("svg")
.attr("id", "boroughs")
.style("width", width + "px")
.style("height", height + "px")
.selectAll("path")
.data(nyb.features)
.enter().append("path")
.attr("class", function(d){ return d.properties.borough; })
.attr("d", path)
.attr("xlink:href", "http://www.nytimes.com");
});
</script>
</body>
</html>
最佳答案
基本上有两种方法可以将链接添加到 SVG 形状:
使用
<svg:a>
元素。正如您在问题中已经指出的那样,如果它嵌套在应该添加链接的元素中,这将不起作用。很像 HTML 中的同名元素,您需要将<a>
包裹起来围绕应附有链接的内容。var map = container.append("svg") .attr("id", "boroughs") .style("width", width + "px") .style("height", height + "px") .selectAll("path") .data(nyb.features) .enter() .append("a") // The link goes here... .attr("xlink:href", "http://www.nytimes.com") .append("path") // ...wrapping the path. .attr("class", function(d){ return d.properties.borough; }) .attr("d", path);
如 Cyril's answer 中所述你可以附加一个 JavaScript 事件监听器处理
click
事件。
关于javascript - 如何在 D3.js 中添加地理链接(创建为 json 路径)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34716453/