我正在绘制地图并在其上附加鼠标事件。我正在使用 D3 库。
我使用 D3 的"on"函数将鼠标事件处理程序注册到"县路径(每个县)"。发生鼠标事件时,它需要打印出控制台上的日志(即控制台日志),但它不起作用。
下面是整个代码。谢谢!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<script type="text/javascript" src="../d3.v2.js"></script>
<script type="text/javascript" src="../d3.geo.js"></script>
<script src="js/jquery-1.7.1.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jquery-ui-1.8.17.custom.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css">
#counties path {
pointer-events: all;
stroke: #fff;
stroke-width: .25px;
}
/*
#counties path:hover {
stroke: yellow;
fill: orange;
}
*/
#map_legend {
position: relative;
top:0px;
right:0px;
}
</style>
</head>
<body>
<div id="body">
<div id = "map_legend">
<script type="text/javascript">
var width = 960,
height = 500,
centered;
var projection = d3.geo.albersUsa().scale(960*4).translate([800,-50]);
var path = d3.geo.path().projection(projection);
var svg = d3.select("#map_legend").append("svg:svg")
.attr("width", 80) //960
.attr("height", 130); //500
var counties = svg.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.append("g")
.attr("id", "counties");
d3.json("us-counties.json", function(json) {
counties.selectAll("path")
.data(json.features)
.enter().append("svg:path")
.attr("id",function(d,i) { return i;})
.attr("d", path);
});
counties.selectAll("path")
//.attr("pointer-events", "all")
.on("mouseover", function(d) { console.log("path mouseover"); })
.on("mouseout", function(d) { console.log("path mouseout"); })
.on("mousemove", function(d) { console.log("path mouseout");})
.on("touchmove", function(d) { console.log("path mouseout"); })
.on("click", function(d) { console.log("path click"); });
</script>
</div>
</body>
</html>
问题是对d3.json
的异步调用。您正在尝试在没有任何路径可供选择和建立鼠标事件侦听器之前建立它们。尝试将设置侦听器的代码块移动到 d3.json
的回调中。