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

d3.js - How can I set the cursor to hand when mouseover these elements on SVG container?

本文关键字:元素 置光标 鼠标 js- 悬停 SVG d3      更新时间:2023-10-12

我用d3.js在SVG容器上画了一些圆。

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

但是,我不想打印控制台消息,而是想在鼠标悬停在它们上面时将光标更改为指针,并且在鼠标悬停时将光标改回正常箭头。考虑到下面的代码,我该怎么做?

在mouseover上,我知道我需要将样式属性cursor更改为pointer,在mouseout上,我也知道我需要更改为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?
            }
          }
        );

你可以这样做:

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')

为什么不让CSS来处理它呢?

.dots {
  cursor: pointer;
}

你刚才试过这个吗:

    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/

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

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

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