简体   繁体   English

如何在悬停时引用d3js对象并单击

[英]how to reference d3js object on hover and click

I am working with an existing piece of code: 我正在使用现有的代码:

https://plnkr.co/edit/e2kpAaMjTTzmXnE4ghGY?p=preview https://plnkr.co/edit/e2kpAaMjTTzmXnE4ghGY?p=preview

<!DOCTYPE html>

<html>

<meta charset="utf-8">

<head>



<style>



.states {

  fill: none;

  stroke: #fff;

  stroke-linejoin: round;

}



 .county:hover {



    fill: red !important;

  }


svg:hover{

background: black;

}



</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script src="https://d3js.org/d3.v3.min.js"></script>

<script src="https://d3js.org/queue.v1.min.js"></script>

<script src="https://d3js.org/topojson.v1.min.js"></script>

</head>

<body>

<div style="float:left,width:40%" id="click"></div>

 <!-- For Dropdown menu --> 

    <select onchange="Dropdown(this.value)">

      <option >Unemployeement</option>

      <option >Random</option>

    </select>

<script>

$("div").click(function(){

alert("here");

});

var width = 960,

    height = 500;



var color = d3.scale.threshold()

    .domain([0.02, 0.04, 0.06, 0.08, 0.10])

    .range(["#f2f0f7", "#dadaeb", "#bcbddc", "#9e9ac8", "#756bb1", "#54278f"]);



var path = d3.geo.path();



var svg = d3.select("div").append("svg")

    .attr("width", width)

    .attr("height", height);



queue()

    .defer(d3.json, "https://gist.githubusercontent.com/mbostock/4090846/raw/d534aba169207548a8a3d670c9c2cc719ff05c47/us.json")

    .defer(d3.tsv, "unemployment.tsv")

    .await(ready);



function ready(error, us, unemployment) {

  if (error) throw error;



  var rateById = {};



  unemployment.forEach(function(d) { rateById[d.id] = +d.rate; });



  svg.append("g")

      .attr("class", "counties")

    .selectAll("path")

      .data(topojson.feature(us, us.objects.counties).features)

    .enter().append("path")

      .attr("d", path)

        .attr("class", "county")

      .style("fill", function(d) { return color(rateById[d.id]);

      });    

  svg.append("path")

      .datum(topojson.mesh(us, us.objects.states, function(a, b) { return a.id !== b.id; }))

      .attr("class", "states")

      .attr("d", path);

 var object=svg.append("foreignobject");

 var div=object.append("div");

 var tooltip=d3.select("div").append("span")

 .attr("class","ccc")

 .style("z-index", "10")

    .style("visibility", "hidden")

    .style("position", "absolute")   

    .style("text-align","center")     

    .style("width","60px")          

    .style("height", "28px")         

    .style("padding","2px")       

    .style("font","12px sans-serif")    

    .style("background","lightsteelblue") 

    .style("border","0px")    

    .style("border-radius","8px")     

    .style("pointer-events","none") 

 .text("here");



d3.select("div") 

  .on("mouseover", function(){return tooltip.style("visibility", "visible");})

  .on("mousemove", function(){return tooltip.style("top", (event.pageY-10)+"px").style("left",(event.pageX+10)+"px");})

  .on("mouseout", function(){return tooltip.style("visibility", "hidden");});  

 $("span").click(function(){

    alert("The paragraph was clicked.");

});

}

var dropdownMap = {
  'Unemployeement': 'unemployment.tsv',
  'Random': 'random.tsv'
}

function Dropdown(val){

  let file = dropdownMap[val];

  if(!file){
    file = 'unemployment.tsv'
  }

    queue()

    .defer(d3.json,"https://gist.githubusercontent.com/mbostock/4090846/raw/d534aba169207548a8a3d670c9c2cc719ff05c47/us.json")

    .defer(d3.tsv, file)

    .await(ready);

}

</script>

</body>



</html>

There's two areas I'm trying to repair. 我正在尝试修复两个区域。 1. the tooltip. 1.工具提示。 I've been able to get a hover over a particular county, but I don't know how to rectify which county I'm hovering. 我已经能够将鼠标悬停在特定的县上,但是我不知道如何纠正我要悬停在哪个县。 in line 186, I have .text("here"); 在第186行中,我有.text("here"); . I need that to be html .text("<div id='countyid'>text</div>" . however, the tags show up as text, and I can't get the countyid referenced into the id field. 我需要将其设置为html .text("<div id='countyid'>text</div>" 。但是,标记显示为文本,并且我无法在id字段中引用县名。

2.the click. 2.点击。 on line 74, I have an alert, based on the click. 在第74行,基于点击,我有一个警报。 I need to know which county I'm clicking on. 我需要知道我要点击哪个县。 it appears I'm missing something that identifies the countyid. 看来我缺少识别县名的内容。

how do I reference them? 我如何引用它们? Thanks. 谢谢。

I'm not familiar with d3.js, however with a little reading of the docs and some fiddling I made you a new Plunker . 我对d3.js并不熟悉,但是通过阅读一些文档和一些摆弄,我使您成为了一个新的Plunker

Your were binding all your tooltip and click events to your main div . 您正在将所有工具提示和click事件绑定到主div I reworked your code and set the events to trigger on the "paths" that are the counties. 我重新编写了您的代码,并将事件设置为在县的“路径”上触发。

Each county now shows it's id when you mouse over it, the tooltip has the markup you wanted (the id of the div is the id of the county. I used the id instead of the word "text" as the content of the div) and when you click a county it alerts it's id . 现在,当您将鼠标悬停在每个县时,每个县都将显示其id ,工具提示具有您想要的标记(div的id是县的id 。我使用id代替单词“ text”作为div的内容)当您单击一个县时,它会提示它的id

That should get you started. 那应该让您开始。

Add mouseover and mouseclick handlers associated with SVG bound to polygon data and use your tooltip definition from there. 添加与绑定到面数据的SVG相关的mouseovermouseclick处理程序,然后从那里使用工具提示定义。 Note that you can pass hovered/clicked polygon to that callback. 请注意,您可以将悬停/单击的多边形传递给该回调。 The text() called on tooltip is not needed. 不需要在tooltip上调用的text() This is major change: 这是主要变化:

svg.append("g")
    .attr("class", "counties")
    .selectAll("path")
    .data(topojson.feature(us, us.objects.counties).features) // us has list of polygons
    .enter().append("path")
    .attr("d", path)
    .attr("class", "county")
    .style("fill", function(d) {
        return color(rateById[d.id]);
    }).on("mouseover", function(county) {
        // change tooltip content here
        tooltip.html("County ID " + county.id); 
    }).on("click", function(county) {
        // define your on-click reaction here
        alert("County ID clicked " + county.id); 
    });

Working code is here: https://plnkr.co/edit/qHHczyK57H2QzNG6eIik?p=preview 工作代码在这里: https//plnkr.co/edit/qHHczyK57H2QzNG6eIik?p = preview

Disclaimer: I have introduced minimal set of changes to your code (plus removed empty lines for readabilty) to address your issue. 免责声明:我已对您的代码进行了最少的更改集(为了便于阅读,还删除了空行)以解决您的问题。 Any other issues your code may expose are left intact. 您的代码可能暴露的任何其他问题均保持不变。

(PS: I should have posted partial answer before taking break ;) (PS:我应该在休息之前发布部分答案;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM