d3.js - 当鼠标悬停在SVG容器上的这些元素时,如何设置光标?

Saq*_*Ali 15 javascript css svg mouseover d3.js

我已经使用d3.js在SVG容器上绘制了一些圆圈.

我已成功在这些圆圈上设置鼠标悬停行为以打印简单的控制台消息.当我鼠标悬停(和mouseout)时,我看到那些控制台消息,所以我知道它们正常工作.

但是,我不想打印那些控制台消息,而是在鼠标悬停时将光标更改为手,我想在鼠标移出时将光标更改回正常箭头.鉴于我的代码如下,我该怎么做?

在鼠标悬停时,我知道我需要将样式属性更改cursorpointer和鼠标输出,我知道我需要将其更改为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?
            }
          }
        );
Run Code Online (Sandbox Code Playgroud)

Cyr*_*ian 23

你可以这样做:

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

这里工作代码

  • 你真的不需要在mouseout上设置样式.原因是如果鼠标位于元素上方,则应用光标样式.否则,事实并非如此.因此在这种情况下没有理由动态设置样式.您也可以在初始化时设置样式. (4认同)

Ger*_*ado 21

你为什么不简单地让CSS处理它?

.dots {
  cursor: pointer;
}
Run Code Online (Sandbox Code Playgroud)

  • 显然这是最好的解决方案,除非您需要根据代码中的其他变量更改光标样式。 (2认同)

Gre*_*i64 11

你刚试过这个:

    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");
Run Code Online (Sandbox Code Playgroud)

因为当您将光标定义为对象的指针时,当您"鼠标悬停"时,指针将变为指针.

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


Dou*_*ghy 5

在这种情况下,动态设置样式没有任何意义。如果鼠标悬停在元素上,则将应用光标样式。否则,您将鼠标悬停在另一个元素上,并将应用该元素的光标样式。因此,没有理由根据鼠标悬停事件动态设置样式。您最好只在初始化时设置样式。

myCircle.style("cursor", "pointer");
Run Code Online (Sandbox Code Playgroud)

或者,只需将CSS文件中的样式设置为另一个答案即可。