我在D3.js图表中成功获得了十字准线,但问题是我只获得垂直线,我如何为水平线添加代码?
Image of chart
JSFiddle code图表没有在JSFiddle中绘图
基本上添加垂直线十字准线的代码如下: -
var vertical = d3.select("body")
.append("div")
.attr("class", "remove")
.style("position", "absolute")
.style("z-index", "19")
.style("width", "1px")
.style("height", "450px")
.style("top", "47px")
.style("bottom", "1px")
.style("left", "8px")
.style("background", "#000");
我可以同样添加水平十字准线吗?
P.S。还想要一种方法来保持这条垂直线只在图表区域,但是整个身体,即左右图表旁边的空白区域。
答案 0 :(得分:5)
你的方法太复杂了。这更简单:
首先,创建一个透明矩形以获得鼠标移动:
var transpRect = svg.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.attr("fill", "white")
.attr("opacity", 0);
然后,创建行:
var verticalLine = svg.append("line")
.attr("opacity", 0)
.attr("y1", 0)
.attr("y2", height)
.attr("stroke", "black")
.attr("stroke-width", 1)
.attr("pointer-events", "none");
var horizontalLine = svg.append("line")
.attr("opacity", 0)
.attr("x1", 0)
.attr("x2", width)
.attr("stroke", "black")
.attr("stroke-width", 1)
.attr("pointer-events", "none");
最后,将行放在mousemove
:
transpRect.on("mousemove", function(){
mouse = d3.mouse(this);
mousex = mouse[0];
mousey = mouse[1];
verticalLine.attr("x1", mousex).attr("x2", mousex).attr("opacity", 1);
horizontalLine.attr("y1", mousey).attr("y2", mousey).attr("opacity", 1)
}).on("mouseout", function(){
verticalLine.attr("opacity", 0);
horizontalLine.attr("opacity", 0);
});
这是你的小提琴:https://jsfiddle.net/xrf1ro1a/
PS:为了避免杀死你的工具提示,我将mousemove
同时放在矩形和svg上,这会使线条超出图表区域。为避免这种情况,请将pointer-events = none
设置为图表区域外的元素。