2017-08-31 115 views
-1

将鼠标悬停在该城市的圆上时,以下代码会生成一个带城市名称的文本框。如何删除鼠标悬停效果并在地图最初加载时将其永久保留?谢谢。如何在D3中保留文本框

// Place Capital Cities the Map 
     svgContainer.selectAll("circle") 
      .data(capitalCities) 
      .enter().append("circle") 
      .attr("id", function(d, i) { return d.name.toLowerCase(); }) 
      .attr("cx", function(d, i) { return projectionType(d.coordinates)[0]; }) 
      .attr("cy", function(d, i) { return projectionType(d.coordinates)[1]; }) 
      .attr("r", "10") 
      .attr("stroke", "black") 
      .attr("stroke-width", "2px") 
      .style("fill", "#FFFF00") 
      .text("City Name:" + "<br />" + cityName); 


     // Mouse Over a City tells us the name 
     d3.selectAll("circle").on("mouseover", function() { 

      // Select the circle being moused over 
      circle = d3.select(this); 

      // Extract the name of the city from the bound data 
      cityName = circle.data()[0].name; 

      // Update and place the tooltip with the city name. 
      div.html("City Name:" + "<br />" + cityName) 
       .style("left", (d3.event.pageX + 9) + "px") 
       .style("top", (d3.event.pageY - 43) + "px") 
       .style("display", "inline"); 
     }) 

     // Mouse Out of a City removes the text 
     d3.selectAll("circle").on("mouseout", function() { 

      // Make the tooltip invisible 
      div.style("display", "none"); 

     }) 

     }); 
+0

您可以只追加一个文本元素,https://www.dashingd3js.com/svg-text-element – TimCodes

+0

感谢您回复TimCodes。我编辑了上述帖子,以反映我进行更改的位置,但现在根本不显示任何文本。 – heisenberg

回答

0

对于初学者,只需删除“mouseout”事件。然后该div不会在mouseout上消失(您也可以将该函数绑定到其他事件,例如按钮)。但是,正如蒂姆所说,如果你希望文本在每个城市永久保留(即不在鼠标悬停事件上),那么div方法可能不是要走的路(除非你需要很多div元素)。

鼠标悬停事件移动单格和更改文本,如果你想旁边的每个“圈”的文/城市永久,那么文本元素可能是一个有点简单:

var text = svgContainer.selectAll("text") 
.data(circleData) 
.enter() 
.append("text"); 

var textLabels = text 
.attr("x", function(d) { return d.cityX; }) 
.attr("y", function(d) { return d.cityY; }) 
.text(function (d) { return "City Name:" + "<br />" + d.cityName }) 
.attr("font-family", "sans-serif") 
.attr("font-size", "20px") 
.attr("fill", "red"); 

显然修改这适合您的数据结构并将标签移到城市旁边而不是顶端。

相关问题