javascript - 样式化 d3 的工具提示

标签 javascript d3.js mouseevent

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

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()
      //...

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

最佳答案

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

div.tooltip {   
    position: absolute;         
    etc...          
}

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

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

div 的不透明度为 0。然后只需在 mouseovermousemove 上显示工具提示即可:

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

您可以使用 HTML 标记在工具提示中设置文本样式,使其变为粗体、斜体等。最后,我们使工具提示在鼠标移出时消失(就像您所做的那样):

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

由于 0 不透明度的 div 仍然在页面中占用空间,更好的方法是将其 display 属性从 none 更改为 blockmouseover 期间,并在 mouse out 返回到 none

关于javascript - 样式化 d3 的工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35652760/

相关文章:

javascript - 如何将多个angularjs文件编译成单个应用程序文件

events - 将 EventHandler 添加到包含在 VBox 中的 TilePane 中的 ImageView?

c# - 使用 C# 鼠标事件从服务器向客户端发送标志

java - 如何在延迟后触发第二个事件处理程序

javascript - jQuery Dialog 按钮改变颜色内联

javascript - 显示/隐藏层 onclick 不一致

Javascript:一旦 'class/object' 变为 'extended' ,是否可以使用不同的基数 'class/object' 重新扩展它?

javascript - 如何在 d3 力有向图中将链接渲染为弯头连接器

javascript - dc.js 热图取消选择颜色

javascript - 带有排斥圆圈的圆图