首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >D3.js svg元素遍历

D3.js svg元素遍历
EN

Stack Overflow用户
提问于 2013-06-25 04:08:51
回答 1查看 777关注 0票数 0
代码语言:javascript
复制
//build legend key
        var svgContainer = d3.select("#TMLegend").append("svg")
              .attr("width", 972)
              .attr("height", 30);
        var width = 35, height = 10, x = 0;

        for(var e =0; e < root.children.length; e++){           
           svgContainer
              .append("rect")
              .attr("x", 0)
              .attr("y", 10)
              .attr("width", width)
              .attr("height", height)
              .attr("transform", "translate("+(36*x++)+",0)")
              .style("fill", function(){
                return colorArr[root.children[e].name];
              })
              .attr("title", function(){
                return root.children[e].name;
              })

              .text(function(){
                return root.children[e].name;
              });  
        }
d3.selectAll("#TMLegend rect").on("mouseover",function () {
        var title = d3.select(this).text();
        $("#TMLegendPopUp").show().html("<h4>"+title+"</h4>");
          //Popoup position
         $(document).mousemove(function(e){
             var popLeft = e.pageX + 10;
             var popTop = e.pageY + -90;
             $("#TMLegendPopUp").css({"left":popLeft,"top":popTop});
             $("#TMLegendPopUp h4").css({"background": colorArr[title], "margin":0});
        });    
    });

上面的代码是我尝试以id为TMLegend的div为目标,并试图深入到svg:rect.attr(' id '),以获取rect元素id的内容。从那时起,我不再放置ID Attr(),而是现在以text()为目标。当rect节点是硬编码的时候,这段代码可以工作,但是当我使用D3生成它们时就不行了。有没有人有办法用D3动态获取rect元素的文本?

硬编码的html如下所示:

代码语言:javascript
复制
        <div id="TMLegend">
       <svg width="972" height="30">      

农产品、贵金属、矿产、建材、纺织品,非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-06-25 05:27:30

这与预期不谋而合,因为d3.select只选择第一个匹配的元素。您需要使用d3.selectAll来选择图例中的所有矩形,然后在鼠标悬停在每个矩形上时使用d3.select(this)来定位每个矩形。根据我认为您正在尝试实现的目标,您需要以下内容:

代码语言:javascript
复制
d3.selectAll("#TMLegend rect").on("mouseover",function () { 
  $("#TMLegendPopUp").show()
    .html("<h4 style='margin:0'>" + d3.select(this).attr("id") + "</h4>");

    //Popoup position
   $(document).mousemove(function(e){
       var popLeft = e.pageX + 10;
       var popTop = e.pageY + -90;
       $("#TMLegendPopUp").css({"left":popLeft,"top":popTop});
   }); 
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17284180

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档