Javascript 造型d3和xB4;工具提示

Javascript 造型d3和xB4;工具提示,javascript,d3.js,mouseevent,Javascript,D3.js,Mouseevent,我在地图上通过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

我在地图上通过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")
    });
我的特色是:

var feature = g.selectAll("circle")
      .data(myData.features)
      .enter()
      //...

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

你可以用CSS来设置工具提示的样式。您可以在一个单独的
.css
文件中、在一个
标记中或使用d3来完成此操作,方法与提供工具提示可见性相同。类似于
.style(“背景”,“rgba(179,107,0,0.5)”)
这就是我喜欢做的事情。首先,我使用名为“tooltip”的类的div设置工具提示的CSS样式:

然后我设置了一个工具提示变量(这里,
svgId
是添加SVG的元素的ID,与选择“body”没有太大区别):

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);
});
由于不透明度为
0
的div仍然占据页面空间,因此更好的方法是在
鼠标悬停期间将其
显示
属性从
更改为
,并在
鼠标悬停
中返回到

var tooltip = d3.select("#svgId").append("div") 
    .attr("class", "tooltip")               
    .style("opacity", 0);
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);
});
selection.on("mouseout", function(d) {
    tooltip.style("opacity", 0);
});