2013-09-24 66 views
12

我有一张D3渲染的SVG图形中的美国州和州的地图。每条路径都有绑定到它的鼠标悬停,鼠标悬停和点击事件,以及设置为路径ID的FIPS县代码。d3 - 触发鼠标悬停事件

我有一个jQuery自动完成输入,用户可以输入州或县的名称。鉴于该输入使相应的FIPS ID可用,如何以编程方式触发mouseover事件?

回答

2

构建您的JavaScript,以便mouseover事件调用JavaScript函数,然后您可以随时调用相同的函数。

7

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

说你必须通过

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); 
}); 

建成了D3的路径和改变填充和笔触颜色

var mapMouseOver(d){ 

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

} 

通常,大多数教程说使用鼠标悬停事件处理

d3.select(this)... 

但实际上使用该值也适用。如果你有一个事件处理程序,让你的节点的ID,并通过

触发它
$("#someDropdownSelect").change(someEventHandler) 

function someEventHandler(){ 

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

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

} 

将执行基于一个下拉选择鼠标悬停事件

5

您可以通过直接调度的情况下做到这一点所需元素:

var event = document.createEvent('SVGEvents'); 
event.initEvent(eventName,true,true); 
element.dispatchEvent(event); 

见更多的关于blog post

+0

这很好。 –

2

史蒂夫Greatrex的解决方案为我工作,直到iOS 9,但不是iOS 10.

调试我的代码和一些研究后,似乎问题在于,根据此documentation弃用了createEvent和initEvent函数。

写这个的新方法是:

有关创建和触发事件与事件的构造的新途径
var event = new MouseEvent('SVGEvents', {}); 
element.dispatchEvent(event); 

更多的解释可以发现here

相关问题