【问题标题】:d3 - trigger mouseover eventd3 - 触发鼠标悬停事件
【发布时间】:2013-09-30 06:19:36
【问题描述】:

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

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

【问题讨论】:

    标签: d3.js svg dom-events mouseover


    【解决方案1】:

    Steve Greatrex 的解决方案在 iOS 9 之前对我有效,但在 iOS 10 上无效。

    在调试了我的代码并进行了一些研究之后,问题似乎是 createEvent 和 initEvent 函数已根据此documentation 被弃用。

    新的写法是:

    var event = new MouseEvent('SVGEvents', {});
    element.dispatchEvent(event);
    

    有关使用事件构造函数创建和触发事件的新方法的更多说明,请参见here

    【讨论】:

      【解决方案2】:

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

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

      blog post中查看更多详细信息

      【讨论】:

        【解决方案3】:

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

        假设你有一个通过构建的 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);
        });
        

        以及改变填充和描边颜色的鼠标悬停事件处理程序

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

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

        【讨论】:

          【解决方案4】:

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

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-01-14
            • 1970-01-01
            • 2012-04-30
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多