【问题标题】:Tooltip with own event listeners带有自己的事件侦听器的工具提示
【发布时间】:2018-06-28 20:33:58
【问题描述】:

对不起,如果这是部分重复,找不到任何满意的答案。

我有一个 d3 图,它由一条带点的线组成。我的观点有使工具提示出现/消失的事件,见下文:

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

var points = g.selectAll(".point")
    .data(data).enter().append("rect")
    .attr("class", "point")
    .on('mouseover', function(d, i) {

        var xPos = parseFloat(d3.select(this).attr('x')) + margin.left
        var yPos = parseFloat(d3.select(this).attr('y')) + margin.top - 20

        div.interrupt();
        div
            .style("left", xPos + 'px')
            .style("top", yPos + 'px')
            .style('opacity', 0.9);

        div.html('<p><strong>Upper Text</strong></p><p>Lower Text</p>');
    })
    .on('mouseout', function(d, i) {
        div
            .transition().delay(1000)
            .style("opacity", 0);
    });

这很好用:当我将鼠标悬停在它上面时,工具提示会出现在我的位置附近,并在我将光标移开 1 秒后消失。

我想要什么:如果我将鼠标悬停在工具提示本身上,则中断工具提示渐隐,然后如果我将光标移开,则使其消失。

(即如果工具提示有文本和链接,我希望用户能够将光标从该点移动到工具提示,然后只要光标在它上面就保持工具提示可见)

我试过了:

var div = d3.select("body")
   .append("div")
   .attr("class", "tooltip")
   .style("opacity", 0)
   // on mouseover, interrupt the transition triggered when I moved
   // the cursor away from the point and over the tooltip
   .on('mouseover', function() {
       d3.select(this)
           .interrupt();
   })
   // on mouseout, quickly fade the tooltip away
   .on('mouseout', function() {
       d3.select(this)
           .transition().duration(100)
           .style("opacity", 0.0);
   });

但似乎工具提示不包含我尝试绑定到它的事件侦听器。

我的问题是:如何将事件侦听器添加到工具提示中,以便将光标从点移动到工具提示时它仍然可见?

【问题讨论】:

  • 您的解决方案对我有用。看看我刚刚创建的这个演示:jsfiddle.net/ouosssp2
  • 感谢您的确认。您的评论帮助我找到了原因,我将其发布为答案。

标签: javascript d3.js tooltip dom-events


【解决方案1】:

正如 Gerardo 所指出的,代码确实有效。我认为没有的原因是因为我的 css 如下:

.tooltip {
    position: absolute;
    text-align: center;
    width: auto;
    height: auto;
    padding: 5px;
    border: 0px;
    border-radius: 8px;
    pointer-events: none;
}

pointer-events: none 显然禁用了工具提示中的所有 DOM 事件。删除此行解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-12-05
    • 2023-03-30
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    相关资源
    最近更新 更多