d3.js - 如何在SVG容器上将鼠标悬停在这些元素上时将光标设置为手形?

29

我使用d3.js在SVG容器上绘制了一些圆形。

我已经成功地为这些圆形设置了鼠标悬停行为以打印简单的控制台消息。当我悬停(和移开鼠标)时,我看到那些控制台消息,所以我知道它们正常工作。

然而,我想在悬停时将光标更改为手指,并在移出时将光标更改回普通箭头,而不是打印控制台消息。给定下面的代码,我该怎么做?

在鼠标悬停时,我知道我需要将样式属性cursor更改为pointer,在鼠标移出时,我知道我需要将其更改为default,但我不知道应该如何编写语法。请问有人可以解释给我吗?下面是我的代码。

        var myCircle = svgContainer.selectAll(".dots")
          .data(myDataList).enter().append("circle")
          .attr("class", "dots")
          .attr("cx", function(d, i) {return d.centerX})
          .attr("cy", function(d, i) {return d.centerY})
          .attr("r", 5)
          .attr("stroke-width", 0)
          .attr("fill", function(d, i) {return "red"})
          .style("display", "block");



        myCircle.on({
            "mouseover": function(d) {
              console.log('Hello World!'); // What do I change this to?
            },
            "mouseout": function(d) {
              console.log('Goodbye World!'); // What do I change this to?
            }
          }
        );
4个回答

38

你可以这样做:

myCircle.on({
      "mouseover": function(d) {
        d3.select(this).style("cursor", "pointer"); 
      },
      "mouseout": function(d) {
        d3.select(this).style("cursor", "default"); 
      }
    });

这里提供 工作代码

或者

您可以在CSS中简单地解决这个问题。

myCircle.style('cursor', 'pointer')


6
您真的不需要在鼠标移出时设置样式。原因是如果鼠标悬停在元素上方,光标样式会自动应用。否则,光标样式就不会生效。因此,在这种情况下没有必要动态设置样式。最好在初始化时直接设置样式。 - Doughy
1
{btsdaf} - Cyril Cherian
1
这不是一个好的答案。请参考下面使用CSS的答案。最好的方法是只需设置myCircle.style('cursor', 'pointer') - Chris Conlan

30

为什么不直接让CSS处理呢?

.dots {
  cursor: pointer;
}

2
{btsdaf} - Doughy

15

你刚刚试过这个:

    var myCircle = svgContainer.selectAll(".dots")
      .data(myDataList).enter().append("circle")
      .attr("class", "dots")
      .attr("cx", function(d, i) {return d.centerX})
      .attr("cy", function(d, i) {return d.centerY})
      .attr("r", 5)
      .attr("stroke-width", 0)
      .attr("fill", function(d, i) {return "red"})
      .style("display", "block")
      .style("cursor", "pointer");

因为当你将光标定义为对象的指针时,当你“鼠标悬停”时,指针就变成了指针。

这里看一个例子:https://jsfiddle.net/oj5vubxn/2/


14

在这种情况下动态设置样式没有意义。如果鼠标悬停在元素上,则应用光标样式。否则,您正在悬停在另一个元素上,并且应用该元素的光标样式。因此,没有理由基于mouseover事件动态设置样式。你最好在初始化时就设置样式。

myCircle.style("cursor", "pointer");

或者,就像另一个回答所指示的那样,在CSS文件中设置样式。


1
这是D3范式中最好的答案。 - Chris Conlan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接