2016-04-23 68 views
1

我喜歡使用this tooltipthis answer但是我不知道如何將數據綁定到它。D3將數據綁定到SVG工具提示

在這個例子中,我想有兩個圓圈,在懸停時顯示它們的大小值爲文本。

watch.csv

circle,size 
green,5 
yellow,10 

代碼

d3.csv("watch.csv", function(error, watch) { 

    var tooltip = d3.select("body") 
    .append("div") 
    .style("position", "absolute") 
    .style("z-index", "10") 
    .style("visibility", "hidden") 
    .text(function(d) { return d.size; }) //TRYING THIS 

    var sampleSVG = d3.select(".example_div") 
    .append("svg:svg") 
    .attr("class", "sample") 
    .attr("width", 300) 
    .attr("height", 300); 

    d3.select(".example_div svg") 
    .data(watch)     //AND THIS 
    .enter()      
    .append("svg:circle") 
    .attr("stroke", "black") 
    .attr("fill", "aliceblue") 
    .attr("r", 30) 
    .attr("cx", 52) 
    .attr("cy", 52) 
    .on("mouseover", function() { 
     return tooltip.style("visibility", "visible"); 
    }) 
    .on("mousemove", function() { 
     return tooltip.style("top", (d3.event.pageY - 10) + "px").style("left", (d3.event.pageX + 10) + "px"); 
    }) 
    .on("mouseout", function() { 
     return tooltip.style("visibility", "hidden"); 
    }); 


}); 

Plunker

回答

0

更改您的提示var此:

var tooltip = d3.select("body") 
    .append("div") 
    .attr("class", "someTooltip") 
    .style("opacity", 0); 

使用選擇器.someTooltip在CSS中設置工具提示。

而改變這一切的「mouseove」,「鼠標移動」和「鼠標移開」:你需要添加jQuery和醉意這是一個jQuery插件

.on("mousemove", function(d) { 
    tooltip.html("The size is: " + d.size) 
    .style("top", (d3.event.pageY - 10) + "px") 
    .style("left", (d3.event.pageX + 10) + "px") 
    .style("opacity", 1); 
}).on("mouseout", function(){ 
    tooltip.style("opacity", 0); 
}); 
0

第一。

<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.2.min.js"></script> 
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.tipsy/1.0.3/jquery.tipsy.js"></script> 

醉意CSS

<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.tipsy/1.0.3/jquery.tipsy.css" rel="stylesheet" type="text/css" /> 

接下來,您需要將數據綁定到醉意jQuery的方式是這樣的。

$('svg circle').tipsy({ //select all circles 
    gravity: 'w', 
    html: true, 
    title: function() { 
     var d = this.__data__;//get the data from the dom 
     return 'Hi there! My color is <span style="color:' + d.circle + '">' + d.size + '</span>'; //make the tipsy tool tip using the data 
    } 
    }); 

刪除所有提示這樣的代碼爲不需要:

.on("mouseover", function() { 
     return tooltip.style("visibility", "visible"); 
    }) 
    .on("mousemove", function() { 
     return tooltip.style("top", (d3.event.pageY - 10) + "px").style("left", (d3.event.pageX + 10) + "px"); 
    }) 
    .on("mouseout", function() { 
     return tooltip.style("visibility", "hidden"); 
    }); 

刪除此

var tooltip = d3.select("body") 
    .append("div") 
    .style("position", "absolute") 
    .style("z-index", "10") 
    .style("visibility", "hidden") 
    .text(function(d) { return d.size; }) //TRYING THIS 

所以,你的代碼看起來像這樣here