Styling d3´s tooltip

為{幸葍}努か 提交于 2019-11-29 12:08:32

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: absolute;         
    etc...          
}

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);

The div has 0 opacity. Then it's just a matter of showing the tooltip on mouseover or mousemove:

selection.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);
});

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):

selection.on("mouseout", function(d) {
    tooltip.style("opacity", 0);
});

Since the div with 0 opacity still takes space in the page, a better approach is changing its display property from none to block during the mouseover, and back to none in the mouse out.

You can style the tooltip with CSS. You could do that in a separate .css file, in a <style> tag, or with d3 the same way you give the tooltip visibility. Something like .style("background", "rgba(179, 107, 0, 0.5)")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!