我有两个大小相同的图(svg1和svg2)。我想同步鼠标悬停即。当用户将鼠标悬停在sgv1点[x0,y0]时,我希望将这些值显示为两个图上的叠加。我的问题是我从原始数据中提取x0,y0和值,并可以通过console.log打印它,但没有叠加。以下是我的代码中的相应片段:
<script>
...
function drawplots(plot){
var focus1,focus2;
if (plot==1) {thisdata=data1; thissvg=svg1;focus=focus1;}
else {thisdata=data2; thissvg=svg2;focus=focus2;}
...
...
focus=thissvg.append("g").attr("class","focus").style("display","none")
.append("circle").attr("r",4.5).append("text")
.attr("x",9).attr("dy",".35em");
thissvg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() { focus.style("display", null ); })
.on("mouseout" , function() { focus.style("display", "none"); })
.on("mousemove", function() {
var x0 = scalex0.invert(d3.mouse(this)[0]);
var index=bisectdata(thisdata,x0);
var y0 = (thisdata[index])[1];
var ypos=scaley0(y0);
var xpos=scalex0(x0);
var fe = d3.format(".1f keV");
var fs = d3.format("s");
var textvalue="[ "+fe(x0)+" , "+fs(y0)+" ]";
console.log(plot,textvalue);
focus.attr("transform", "translate(" + xpos + "," + ypos + ")");
focus.select("text").text(textvalue);
});
}
...
</script>
<body>
<div id="plot1">
<div id="plot2">
svg1=d3.selectAll("#plot1").append("svg").attr("width",width).attr("height",height);
svg2=d3.selectAll("#plot2").append("svg").attr("width",width).attr("height",height);
</body>
那么我如何使用相同的函数在两个不同的svgs上进行鼠标悬停事件?
感谢。
答案 0 :(得分:0)
除非我误解了你的问题,否则不是那么简单......
function mouseover (){
// this will be the element the event is fired on
//get the position using d3.event if relevant
rect1.style({
opacity: 1
});
// perform some other translation manipulation here if needed
rect2.style({
opacity: 1
})
//or you could d3...selectAll('rect') and then perform operations on all at the same time
}
var rect1 = d3...append("rect").on('mouseover', mouseover);
var rect2 = d3...append("rect").on('mouseover', mouseover);
然后是一个类似于mouseout的共享函数。