【问题标题】:How to add tooltip to an svg graphics element using javascript如何使用 javascript 将工具提示添加到 svg 图形元素
【发布时间】:2019-12-04 17:02:52
【问题描述】:

我有一张 d3.parcoords 图表,想为图表的第一个轴添加工具提示。我正在检索第一个轴 DOM 元素并向其添加 title 属性以使其作为工具提示。没有成功!

用户界面图片

代码如下:

    var segmentAxis = self.pcz.svg.selectAll(".dimension .axis")[0][0];

    segmentAxis.title="Tooltip";

【问题讨论】:

  • 在 SVG 中,工具提示是子元素,而不是属性。
  • @RobertLongson,你能帮我在javascript中做到这一点吗?我很接近但还没有成功!
  • 你知道如何创建一个元素吗?给它文本内容?将其添加为另一个元素的子元素?你坚持以上哪一项?

标签: javascript d3.js svg canvas tooltip


【解决方案1】:

正如罗伯特所说,SVG 不使用title 属性。它有一个 <title> 元素。

https://www.w3.org/TR/SVG11/single-page.html#struct-DescriptionAndTitleElements

如果您想向 SVG 组添加工具提示,则需要为您的组创建一个 <title> 元素。

<g>
  <title>Your tooltip here</title>
  ... other elements...
</g>

D3 代码如下所示:

d3.selectAll('.dimension .axis')[0].append("svg:title").text("Your tooltip here");

【讨论】:

    【解决方案2】:

    我在 Paul LeBeau 回答的帮助下解决了我的问题:

    这是屏幕截图

    代码如下:

            var toolTip=d3.select("#dvAllProfiles").select("svg")
            .append("svg:title")
            .attr("class", "tooltip")
            .style("visibility", "hidden")
            .text("Test Tooltip");
    
            self.pcz.svg.selectAll(".dimension").data([0]).selectAll(".tick")
            .selectAll("*")
            .style("font-size", "12px").style("transform", "rotate(340deg)")
            .on("mouseover", function(d) {
                return toolTip.style("visibility", "visible").style("top", event.pageY+"px").style("left",event.pageX+"px").text(d);
            })
            .on("mouseleave", function(d) {
                return toolTip.style("visibility", "hidden")  
            });
    

    【讨论】:

    • 您不必自己隐藏和显示工具提示。见:jsfiddle.net/6f9wg7ov
    • @PaulLeBeau,我必须仅针对最左侧轴的值显示工具提示。此外,我必须在工具提示中显示他们的全文。如何在不使用 mouseover 和 mouseleave 事件的情况下设置所有这些?
    猜你喜欢
    • 2017-08-03
    • 2019-03-08
    • 2016-08-19
    • 2022-01-07
    • 1970-01-01
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多