//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/SKb8W/7/
對於標籤,這裏是一個有用的例子: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];
(來自Mouse position in D3)
你見過[NVD3](http://nvd3.org/)嗎? –
@LarsKotthoff:謝謝你的建議,但我只限於使用D3庫。使用.selectAll('rect')和.selectAll('line')的 –
,您將選擇剛剛創建的'g'元素中的所有矩形和線條,這是空的。這就是爲什麼你沒有得到這些元素出現。 – tomtomtom