【问题标题】:d3 click handler not working on leaflet map layerd3单击处理程序不适用于传单地图图层
【发布时间】:2015-11-01 04:03:18
【问题描述】:

晚上好。

我已将一系列 d3 点添加到传单地图,然后想在这些点上使用点击处理程序来驱动另一个面板。但我似乎无法让处理程序接听。为什么?

到目前为止,您可以看到该文件: http://jsbin.com/bewudenide/edit?html,output

在leaflet.js的自定义层上生成圆点的代码:

var feature = g.selectAll("circle")
            .data(collection)
            .enter().append("circle")
            .style("stroke", "black")  
            .style("opacity", .6) 
            .style("fill", "steelblue")
            .attr("r", 10); 

我认为这是为鼠标悬停和点击事件添加点击处理程序的简单案例:

feature.on("click", click);
    function click(d) {
        console.log(d.name); 
     }

还有:

feature.on("mouseover", mouse_over);
function mouse_over(d) {
    d3.select(this) 
        .transition()
        .duration(500)
        .style("background", "lightBlue")
        .style("color", "white");
      }

虽然单击功能注册到控制台,但我不清楚为什么 mouse_over 功能不会改变点的样式。我也期待看到指针改变,但它没有。

请原谅我缺乏使用 d3、javascript 或传单的经验。

编辑:

我现在意识到我没有添加一些现有代码使用的 JSON。好像

[{
"index":1,"name":"Adderley Green Surgery","total":276266.2700000001},{
    "index":2,"name":"Alton Surgery","total":416559.8999999998},{
        "index":3,"name":"Apsley Surgery","total":1023757.89999999998}]

【问题讨论】:

  • 在您的 JSBin 中,collectiond3.json 处理程序中为空,可能是因为 JSBin 找不到目标 JSON。进一步诊断该错误有点困难。您能否将您的代码简化为您所面临的特定且可重现的问题的较小示例?
  • 您需要检查 svg 对象的有效样式属性。尝试描边和填充。为什么你期望指针改变?
  • @benjarwar 我不知道如何将示例 JSON 硬编码到 JSBIN 中以便它可以运行。相反,我在问题中添加了 JSON 示例。希望对您有所帮助?
  • @CoolBlue 我从 Udacity 教程中获取了样式属性,该教程提供了添加事件的框架。我怀疑我对指针更改太天真了——我认为这可能是触发“鼠标悬停”时对象之间的自然交互。
  • @elksie5000,你的意思是什么? svg 对象没有背景或颜色样式。毫无疑问,您复制代码的教程是在讨论按钮或其他 HTML 对象,但不是 svg...

标签: javascript d3.js leaflet


【解决方案1】:

如果您使用的是传单 1.0,我认为原因是传单已将“指针事件”设置为“无”: Figure showing SVG within leaflet

这使得点击事件不能被触发。所以解决方法很简单,只要用css将“pointer-event”设置为“all”,就可以了!我已经通过使用传单 1.0 进行了尝试。

指针事件: pointer-events description

【讨论】:

【解决方案2】:

问题是样式属性对 svg 元素无效。
试试……

feature.on("mouseover", mouse_over);
function mouse_over(d) {
    d3.select(this) 
        .transition()
        .duration(500)
        .style("fill", "lightBlue")
        .style("stroke", "white");
      }

或者……

feature.on("mouseover", mouse_over);
function mouse_over(d) {
    d3.select(this) 
        .transition()
        .duration(500)
        .style({fill: "lightBlue", stroke: "white"});
      }  

或者……

feature.on("mouseover", mouse_over);
function mouse_over(d) {
    d3.select(this) 
        .transition()
        .duration(500)
        .attr({fill: "lightBlue", stroke: "white"});
      }  

【讨论】:

    猜你喜欢
    • 2015-08-11
    • 1970-01-01
    • 1970-01-01
    • 2018-02-08
    • 1970-01-01
    • 1970-01-01
    • 2019-12-16
    • 1970-01-01
    • 2021-11-27
    相关资源
    最近更新 更多