我有多个SVG圈子,希望每个圈子都有独特的文字显示在悬停的工具提示中。
我将在Adobe Illustrator中创建我的SVG元素,因此需要一种方法将工具提示的文本绑定到SVG的id。
下面我尝试通过创建一个数组,其中对象“color:white”与SVG圈子的名称相匹配id =“#white”如何将此数据绑定到我的工具提示?
var tooltipText = [
{"color":"white", "text":"About white"},
{"color":"black", "text":"About black"}
]
var tooltip = d3.select('.tooltip').text(function(d) {return tooltipText})
d3.select('#white')
.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");
});
.container {
position: relative;
}
.tooltip {
font-family: Arial;
font-size: 10px;
padding: 10px;
width: 100px;
height: 150px;
border: 1px solid black;
position: absolute;
top: 0;
left: 200px;
visibility: hidden;
background: white;
}
#white {
fill: white;
stroke: black;
stroke-width: 2px
}
#black {
fill: black
}
circle:hover {
stroke: green; !important
fill: orange;
stroke-width: 2px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="container">
<svg>
<g id="selection">
<circle id="white" class="st0" cx="49.2" cy="49.2" r="48.7"/>
<circle id="black" class="st1" cx="128.4" cy="49.2" r="48.7"/>
</g>
</svg>
</div>
<div class="tooltip"></div>
答案 0 :(得分:2)
首先,我们会在mousemove
:
var thisId = d3.select(this).attr("id");
然后,我们遍历您的数组并获得相应的值:
var index;
for(var i = 0; i < tooltipText.length; i++){
if(tooltipText[i].color == thisId){
index= i
}
};
tooltip.html(tooltipText[index].text)
这是您更新的代码段:
var tooltipText = [
{"color":"white", "text":"About white"},
{"color":"black", "text":"About black"}
]
var tooltip = d3.select('.tooltip').text(function(d) {return tooltipText})
d3.selectAll("circle")
.on("mousemove", function(d){
var thisId = d3.select(this).attr("id");
var index;
for(var i = 0; i < tooltipText.length; i++){
if(tooltipText[i].color == thisId){ index= i}
};
tooltip.html(tooltipText[index].text)
.style("visibility", "visible")
.style("top",(d3.event.pageY+10)+"px")
.style("left",(d3.event.pageX+10)+"px");
})
.on("mouseout", function(){
return tooltip.style("visibility", "hidden");
});
&#13;
.container {
position: relative;
}
.tooltip {
font-family: Arial;
font-size: 10px;
padding: 10px;
width: 100px;
height: 20px;
border: 1px solid black;
position: absolute;
top: 0;
left: 200px;
visibility: hidden;
background: white;
}
#white {
fill: white;
stroke: black;
stroke-width: 2px
}
#black {
fill: black
}
circle:hover {
stroke: green; !important
fill: orange;
stroke-width: 2px
}
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div class="container">
<svg>
<g id="selection">
<circle id="white" class="st0" cx="49.2" cy="49.2" r="48.7"/>
<circle id="black" class="st1" cx="128.4" cy="49.2" r="48.7"/>
</g>
</svg>
</div>
<div class="tooltip"></div>
&#13;