【问题标题】:How do I refer to a second text element in a second svg如何在第二个 svg 中引用第二个文本元素
【发布时间】:2013-05-14 04:57:12
【问题描述】:

我是 D3 和 js 的新手,我不知道如何在第二个 svg 元素中引用第二个文本元素(不确定元素是否是正确的术语)。

我有两个 svg 元素,一个是网络图(带有节点和链接),一个是散点图(带有纬度/经度位置)。网络图中的节点和散点图矩阵中的矩形都在 svg 组中具有与之关联的文本元素。我需要区分鼠标悬停事件中的两个文本元素,但我不知道该怎么做。

每个都使用不同的源数据:graph.nodes 用于网络图,graph.locs 用于散点图。两者都有“位置”类,用于在鼠标悬停期间建立两者之间的连接。 svg 称为“svg”和“svg2”,但组均称为“g”,文本元素均称为“text”。

我已经发布了一个 jsFiddle 示例,http://jsfiddle.net/JVAdams/LXFMx/。例如,当我将鼠标悬停在网络图中的一个节点上时 (Sally),我希望放大散点图中相应位置的文本 (TorontoON)。这是一段sn-p代码

var node = svg.selectAll(".node")
    .data(graph.nodes)
    .enter().append("g")
    .attr("class", function(d) { return "node " + d.name + " " + d.location; })
    .call(force.drag)
    .on("mouseover", function(d) { 
        d3.select(this).select("circle").style("stroke-width", 6); 
        d3.select(this).select("circle").style("stroke", "orange"); 
        d3.select(this).select("text").style("font", "20px sans-serif");
        d3.selectAll("rect." + d.location).style("stroke-width", 6);
        d3.selectAll("rect." + d.location).style("stroke", "orange");
    // this line doesn't work
    d3.selectAll("text." + d.location).style("font", "20px sans-serif");
        d3.selectAll("tr." + d.name).style("background-color", "orange");
        })
    .on("mouseout",  function(d) { 
        d3.select(this).select("circle").style("stroke-width", 1.5); 
        d3.select(this).select("circle").style("stroke", "gray"); 
        d3.select(this).select("text").style("font", "12px sans-serif");
        d3.selectAll("rect." + d.location).style("stroke-width", 1.5);
        d3.selectAll("rect." + d.location).style("stroke", "black");
        d3.selectAll("text." + d.location).style("font", "12px sans-serif");
        d3.selectAll("tr." + d.name).style("background-color", "white");
        });

代替不符合我要求的行,我尝试了多种方法来正确引用散点图的文本元素,但均未成功:

    d3.selectAll("mapit.text." + d.location).style("font", "20px sans-serif");
    d3.selectAll("g.text." + d.location).style("font", "20px sans-serif");
    d3.selectAll("svg2.text." + d.location).style("font", "20px sans-serif");
    d3.selectAll("svg2.g.text." + d.location).style("font", "20px sans-serif");

有什么建议吗?

【问题讨论】:

    标签: d3.js


    【解决方案1】:

    您尚未向mapit SVG 下的text 元素添加类。

    mapit.append("text")
      .attr("x", function(d) { return xScale(d.long); })
      .attr("y", function(d) { return yScale(d.lat) -5; })
      .attr("font-family", "sans-serif")
      .attr("font-size", "12px")
      .attr("fill", "black")
      .text(function(d) { return d.location; })
      .attr("class", function(d) { return d.location ;});   // <<< Add this line
    

    【讨论】:

    • 谢谢。那行得通。有了这个固定,我也能够修复其他部分。这是更新后的jsFiddle
    猜你喜欢
    • 2016-06-10
    • 2022-11-16
    • 1970-01-01
    • 1970-01-01
    • 2020-06-10
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多