邁克·博斯托克的這個例子顯示了我試圖複製的工具提示(圓圈+文本元素:http://bl.ocks.org/mbostock/3902569)。d3js圖表以十字線作爲工具提示:如何添加兩條在光標位置相交的線
但是,這裏的扭曲是我想擺脫圓圈,並用十字線替換它,保持功能相同。我的部分功能代碼在這裏(第164行和以後粘貼到:http://tributary.io/inlet/8075741)。
儘管添加了第二行元素,但垂直線不會呈現,而水平線按預期工作。
// add cross hairs and floating value on axis
var focus = chart.append("g")
.attr("class","focus")
.style("display", "none");
focus.append("text").attr({"x": 9, "dy": "0.35em"});
// horizontal crosshair
focus.append("line")
.attr({
"x1": 0,
"y1": 0,
"x2": -width + margin.left,
"y2": 0
});
/* failed attempt to dynamically add vertical line
focus.append("line")
.attr({
"x1": d3.mouse(this)[0],
"y1": -height + margin.top*4,
"x2": d3.mouse(this)[0],
"y2": height
});
*/
// failed attempt #2 to hard code vertical line
focus.append("line")
.attr({
"x1": 300,
"y1": -height,
"x2": 300,
"y2": height
})
chart.append("rect")
.attr({"class": "overlay" , "width": width , "height": height})
.on({
"mouseover": function() { focus.style("display", null); },
"mouseout": function() { focus.style("display", "none"); },
"mousemove": mousemove
});
function mousemove() {
var x0 = xScale.invert(d3.mouse(this)[0]),
i = bisectDate(sample2, x0, 1),
d0 = sample2[i-1],
d1 = sample2[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.attr("transform", "translate(" + (width - margin.right) + "," + yScale(d.close) + ")");
focus.select("text").text("$" + d.close);
}
'd3.mouse(this)[0]'不起作用。而是繪製一條簡單的垂直線,並在'mousemove'函數中水平翻譯。 – bits