d3 - 触发鼠标悬停事件

Jas*_*son 14 svg mouseover dom-events d3.js

我有一张由D3渲染的SVG图形中的美国州和县的地图.每个路径都有绑定到它的mouseover,mouseout和click事件,以及设置为路径ID的FIPS县代码.

我有一个jQuery Autocomplete输入,用户可以输入州或县的名称.给定输入,使相应的FIPS ID可用,如何以编程方式触发鼠标悬停事件?

Jas*_*son 7

我想出了答案.主要问题是D3没有trigger像jQuery那样的显式函数.但是,您可以模拟它.

假设你有一条D3路径

d3.json("us-counties.json", function(json){

  thisObj._svg.selectAll("path")
    .data(json.features)
    .enter().append("path")
    .attr("d", thisObj._path)
    .attr("class", "states")
    .attr("id", function(d){
      return d.id; //<-- Sets the ID of this county to the path
    })
    .style("fill", "gray")
    .style("stroke", "black")
    .style("stroke-width", "0.5px")
    .on("dblclick", mapZoom)
    .on("mouseover", mapMouseOver)
    .on("mouseout", mapMouseOut);
});
Run Code Online (Sandbox Code Playgroud)

以及用于更改填充和描边颜色的mouseover事件处理程序

var mapMouseOver(d){

  d3.selectAll($("#" + d.id))
    .style("fill", "red")
    .style("stroke", "blue");

}
Run Code Online (Sandbox Code Playgroud)

通常,大多数教程都说要使用

d3.select(this)...
Run Code Online (Sandbox Code Playgroud)

但实际上使用该值也是有效的.如果您有一个事件处理程序,它可以获取节点的ID,并通过它触发它

$("#someDropdownSelect").change(someEventHandler)

function someEventHandler(){

  //get node ID value, sample
  var key = $(this)
              .children(":selected")
              .val();

  //trigger mouseover event handler
  mapMouseOver({id : key});

}
Run Code Online (Sandbox Code Playgroud)

将根据下拉选择执行鼠标悬停事件


Ste*_*rex 6

您可以通过直接在所需元素上调度事件来实现此目的:

var event = document.createEvent('SVGEvents');
event.initEvent(eventName,true,true);
element.dispatchEvent(event);
Run Code Online (Sandbox Code Playgroud)

在此博客文章中查看更多详细信息


Rob*_*son 3

构造您的 JavaScript,以便鼠标悬停事件调用 JavaScript 函数,然后您可以随时调用相同的函数。