我正在绘制地图并在其上附加鼠标事件。我正在使用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>
答案 0 :(得分:2)
问题是对d3.json
的异步调用。您正在尝试在有任何路径选择并建立它们之前建立鼠标事件侦听器。尝试将设置侦听器的代码块移动到d3.json
。