答案 0 :(得分:2)
//create groups for line and label (and invisible selection area)
var infos = svg.append('g')
.selectAll('rect')
.data(data)
.enter()
.append('g')
//move to datapoint location
.attr('transform',function(d,i){d.x = x(d.date) ; d.y = 0; return "translate(" + d.x + "," + d.y + ")";});
//create and select line "rectangles" (easier than doing actual lines)
infos.append("rect")
.attr('class','line')
.attr('height', height)
.attr('width', 1)
.attr('opacity',0);
//create and select line "rectangles" (easier than doing actual lines)
infos.append("rect")
.attr('class','area')
.attr('height', height)
//should probably do something to make sure they don't overlap, such as measure distance between neighbours and use that as width
.attr('width', width/data.length/2)
.attr('opacity',0)
//move so that the data point is in the middle
.attr('x',-width/data.length/4)
.on('mouseover', function(){
g_elem = this.parentNode;
d3.select(g_elem).selectAll(".line").attr("opacity",1);
})
.on('mouseout', function(){
g_elem = this.parentNode;
d3.select(g_elem).selectAll(".line").attr("opacity",0);
});
对于标签,这是一个有用的示例:http://jsfiddle.net/WLYUY/5/(来自D3.js: Position tooltips using element position, not mouse position?)
使用鼠标坐标可以执行以下操作:
var coordinates = [0, 0];
coordinates = d3.mouse(this);
var x = coordinates[0];
var y = coordinates[1];