javascript - D3 map - 将多边形排除在悬停之外

标签 javascript d3.js svg

在我的 previous question 的后续行动中我正在努力满足我的需求,这个伟大的example map (使用此 dataset )并在悬停时打开自定义工具提示。

我想排除某些状态的悬停。

我希望它们显示在 map 上,但显示为灰色且无响应。

如果我使用svg path,我会为带有悬停的多边形/状态定义一个不同的css class,并为非响应定义一个不同的类。

在我的路径封装在变量( dataset )的情况下,我不知道该怎么做。

function(){
var uStatePaths={id:"HI",n:"Hawaii",d:"M233.08751,(...),554.06663Z"}, (...)
{id:"VT",n:"Vermont",d:"M844.48416,(...),154.05791Z"}, (...)

最佳答案

您可以调整文件 uStates.js 来实现您想要的。创建 draw() 方法的副本并应用一些更改:

  • 传递您想要“禁用”的州 ID 列表。
  • 如果状态 ID 在列表中,请使用“禁用灰色”颜色,而不是使用定义的填充
  • 在事件 Controller 中,检查状态ID是否在列表中;如果是,请不要应用更改(因为该状态将被“禁用”)。

该函数将是这样的:

// notice the new parameter "list" that will contain the disabled states
uStates.drawSpecial = function(id, data, toolTip, list){        

    function mouseOver(d){
      // only show the tooltip if the state is not in the disabled list
      if (list.indexOf(d.id) < 0) {
        d3.select("#tooltip").transition().duration(200).style("opacity", .9);      
        d3.select("#tooltip").html(toolTip(d.n, data[d.id]))  
            .style("left", (d3.event.pageX) + "px")     
            .style("top", (d3.event.pageY - 28) + "px");
        }
    }

    function mouseOut(){
        d3.select("#tooltip").transition().duration(500).style("opacity", 0);      
    }

    d3.select(id).selectAll(".state")
        .data(uStatePaths)
        .enter()
        .append("path")
        .attr("class","state")
        .attr("d",function(d){ return d.d;})
        // if the state id is in the list, select gray instead of the state color
        .style("fill",function(d){ return list.indexOf(d.id) >= 0 ? "#dddddd" : data[d.id].color; })
        .on("mouseover", mouseOver).on("mouseout", mouseOut);
} 

然后,不要调用 draw 方法,而是调用您自己的个性化 drawSpecial 方法。例如,在与 tutorial you linked 中找到的代码类似的代码中,如果您想禁用德克萨斯州 (TX) 和佛蒙特州 (VT),您可以像这样调用该函数:

uStates.draw("#statesvg", sampleData, tooltipHtml, ['TX', 'VT']);

关于javascript - D3 map - 将多边形排除在悬停之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35724822/

相关文章:

json - 如何使用 d3.js 同步加载 JSON 数据?

layout - 避免在平铺的SVG形状之间形成线条

javascript - 如何使用 jQuery 和 Javascript 禁用页面中的所有 AJAX 请求?

javascript - 在浏览器中的 Javascript 代码中,以下情况并不总是正确:: this === window?

javascript - DC.js根据维度计算平均值

javascript - 如何将文本置于圆圈之上?

javascript - pts.js 'NS_ERROR_NOT_AVAILABLE: ' 尝试将图像用于粒子时出错

javascript - 需要一些帮助调试简单的换色器

javascript - KineticJS JavaScript 另存为文件系统选项

javascript - 在文本上应用 Bostock 的换行功能