为样式d3的工具提示 [英] Styling d3´s tooltip
问题描述
我在这样的leafletmap上通过d3实现一个工具提示:
I implement a tooltip over circles placed through d3 on a leafletmap like this:
var tooltip = d3.select("body")
.append("div")
.attr("id", "mytooltip")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
feature.on("mouseover",function(d) {
d3.select(this)
.transition()
.ease("elastic")
.duration(500)
.attr('r', function (d){
return (d.properties.xy * 5)
.style("stroke", "black")
d3.select("#mytooltip")
.style("visibility", "visible")
.text(d.properties.xy1 + " " + d.properties.xy2)
});
feature.on("mousemove", function() {
return tooltip.style("top", (d3.event.pageY-10)+"px")
.style("left",(d3.event.pageX+10)+"px");
});
feature.on("mouseout",function(d) {
d3.select(this)
.transition()
.ease("elastic")
.duration(500)
.attr('r', function (d){
return (d.properties.xy);
})
.style("stroke", "none")
d3.select("#mytooltip")
.style("visibility", "hidden")
});
我的功能是这样的:
var feature = g.selectAll("circle")
.data(myData.features)
.enter()
//...
我不知道如何设置显示的工具提示样式?有没有办法给它一个背景,写一些粗体,斜体,不同的颜色等等?
I wonder how I can style the tooltip that shows up? Is there a way to give it a background, write something in bold, italic, different colors etc?
推荐答案
喜欢做。首先,我设置工具提示的CSS样式,使用一个名为tooltip的类的div:
This is what I like to do. First, I set the CSS style for the tooltip, using a div with a class named "tooltip":
div.tooltip {
position: /*whatever*/;
text-align: /*whatever*/;
white-space: /*whatever*/;
padding: /*whatever*/;
font-size: /*whatever*/;
background: /*whatever*/;
border: /*whatever*/;
border-radius: /*whatever*/;
pointer-events: /*whatever*/;
etc...
}
然后我设置一个工具提示var ,#svgId是您添加svg的元素的ID,与选择body时没有太大区别):
Then I set a tooltip var (here, #svgId is the Id of the element where you append your svg, not much different of selecting "body" as you did):
var tooltip = d3.select("#svgId").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
div有0个不透明度。然后它只是一个问题在鼠标悬停或mousemove显示工具提示。我喜欢mousemove:
The div has 0 opacity. Then it's just a matter of showing the tooltip on mouseover or mousemove. I like mousemove:
feature.on("mousemove", function(d) {
tooltip.html("<strong> Look, I'm bold !</strong> and now I'm
not bold <br> and this is another line! and this
is my data:" + d.whatever)
.style('top', d3.event.pageY - 12 + 'px')
.style('left', d3.event.pageX + 25 + 'px')
.style("opacity", 1);
});
您可以使用HTML标签为工具提示中的文本设置样式,使其粗体,斜体等。 ,最后,我们使鼠标移出时的工具提示消失(如你所做):
You can use HTML tags to style your text inside the tooltip, making it bold, italic etc. And, finally, we make the tooltip disappear on mouseout (as you did):
feature.on("mouseout", function(d) {
tooltip.style("opacity", 0);
});
这篇关于为样式d3的工具提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!