设置d3的工具提示样式

Sto*_*ace 3 javascript mouseevent d3.js

我在通过d3放置在传单地图上的圆上实现了工具提示,如下所示:

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")
    });
Run Code Online (Sandbox Code Playgroud)

我的特点是:

var feature = g.selectAll("circle")
      .data(myData.features)
      .enter()
      //...
Run Code Online (Sandbox Code Playgroud)

我想知道如何设置显示的工具提示的样式?有没有办法给它一个背景,用粗体,斜体,不同的颜色等写东西?

Ger*_*ado 5

这就是我喜欢做的。首先,我使用一个带有名为“ tooltip”的类的div来设置工具提示的CSS样式:

div.tooltip {   
    position: absolute;         
    etc...          
}
Run Code Online (Sandbox Code Playgroud)

然后,我设置了一个工具提示var(此处svgId是您在其中附加SVG的元素的ID,与您选择“ body”时所做的操作没有太大不同):

var tooltip = d3.select("#svgId").append("div") 
    .attr("class", "tooltip")               
    .style("opacity", 0);
Run Code Online (Sandbox Code Playgroud)

div具有0不透明度。然后,只需在mouseover或上显示工具提示即可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);
});
Run Code Online (Sandbox Code Playgroud)

您可以使用HTML标签在工具提示中设置文字样式,使其粗体,斜体等。最后,我们使工具提示在鼠标移开时消失(如您所做的那样):

selection.on("mouseout", function(d) {
    tooltip.style("opacity", 0);
});
Run Code Online (Sandbox Code Playgroud)

由于具有0不透明度的div 仍会在页面中占用空间,因此一种更好的方法是将其display属性从更改为noneblock期间更改为mouseover,然后更改nonemouse out