由于我的程序很复杂,我正在嘲笑一个更简单的版本。这里的目标是单击切换按钮并在缩放坐标和实际坐标之间切换工具提示文本。在update()
函数中,我不知道如何将实际值与d
中的svg
元素相关联。以下是我的代码:
<!DOCTYPE html>
<html>
<head>
<style>
.tooltip {
position: absolute;
pointer-events: none;
z-index: 10;
background: #dddddd;
font: sans-serif;
font-weight: bold;
opacity: 0;
padding: 5px;
border: 2px solid #a1a1a1;
border-radius: 8px;
}
</style>
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
function update() {
/* Need help here */
}
</script>
</head>
<body>
<div id=switchButton>
<button id=switch onclick="update()">Switch</button>
</div>
<hr/>
<div id=scatterDiv></div>
<script>
var width = 800,
height = 800;
var randomX = [],
randomY = [];
for (var i = 0; i <= 25; i++) {
randomX[i] = Math.random() * 400;
randomY[i] = Math.random() * 400;
}
var x = d3.scale.linear()
.domain([d3.min(randomX) - 20, d3.max(randomX) + 20])
.range([0, width]);
var y = d3.scale.linear()
.domain([d3.min(randomY) - 20, d3.max(randomY) + 20])
.range([height, 0]);
var svg = d3.selectAll("#scatterDiv").append("svg")
.attr("width", width)
.attr("height", height);
var tooltip = d3.select("#scatterDiv").append("div").attr("class", "tooltip");
svg.append("g").selectAll("dot")
.data(randomY)
.enter().append("circle")
.attr("cy", function (d) {
return y(d);
})
.attr("cx", function (d, i) {
return x(randomX[i]);
})
.style("fill", "brown")
.attr("r", 6)
.on("mouseover", function (d) {
tooltip.style("opacity", 1);
var tooltipText = "";
tooltipText += "(" + d3.select(this).attr("cx") + ", " + d3.select(this).attr("cy") + ")";
tooltip.html(tooltipText)
.style("left", (d3.event.pageX + 20) + "px")
.style("top", (d3.event.pageY - 40) + "px");
})
.on("mouseout", function (d) {
tooltip.style("opacity", 0);
});
</script>
</body>
</html>