【发布时间】:2014-03-25 13:51:10
【问题描述】:
我已将鼠标悬停事件附加到 SVG 元素内的一个元素(例如一个圆圈)。我还需要一个与 SVG 元素/“背景”本身关联的“mousemove”事件处理程序。但是,它们似乎存在冲突:当鼠标悬停在圆圈上时,附加到圆圈的处理程序不会取代与 SVG 元素本身关联的处理程序。
如何让圆圈的鼠标悬停取代 SVG 元素的事件处理程序?我需要它们,但只希望鼠标悬停在圆圈上触发,并且鼠标移动通过 SVG 元素中其他任何位置的移动触发。
可以在这个 JSFiddle 中看到一个简化的示例:http://jsfiddle.net/aD8x2/(下面的 JS 代码)。如果您单击一个圆圈(开始一条线),然后将鼠标悬停在另一个圆圈上,您将看到与两个事件相关的颜色闪烁,鼠标悬停在该圆圈上时触发。
var svg = d3.select("div#design")
.append("svg")
.attr("width", "500").attr("height", "500");
svg.selectAll("circle").data([100, 300]).enter().append("circle")
.attr("cx", function(d) { return d; })
.attr("cy", function(d) { return d; })
.attr("r", 30)
.on("mouseover", function () {
d3.select(this).attr("fill", "red");
})
.on("mouseout", function() {
d3.select(this).attr("fill", "black");
})
.on("click", function() {
svg.append("line")
.attr(
{
"x1": d3.select(this).attr("cx"),
"y1": d3.select(this).attr("cy"),
"x2": d3.select(this).attr("cx"),
"y2": d3.select(this).attr("cy")
})
.style("stroke-width", "10")
.style("stroke", "rgb(255,0,0)");
});
svg.on("mousemove", function() {
var m = d3.mouse(this);
svg.selectAll("line")
.attr("x2", m[0])
.attr("y2", m[1]);
});
【问题讨论】:
标签: javascript svg d3.js