d3.js如何判断SVG图形是否有一个类?

4

我想在SVG形状中添加一个切换按钮,当点击按钮时缩小它,再次点击时恢复原大小。首先我添加了一个名为collapse的类。如果它有一个collapse类,则我希望删除该类。

g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if(hasClass("collapse")) # HOW DO I DO THIS
    )
4个回答

6
你可以使用 DOM API 来完成这个操作:
g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if(this.classList.contains("collapse")) {
        // ...
        // this.classList.remove('collapse')
      } else {
        // ...
        // this.classList.add('collapse')
      }
    )    

或者使用jQuery:
g.append("circle")
    .classed("collapse", true)
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", color(radius * 0.4 - 10))
    .on("click", (d) ->
      if($(this).hasClass("collapse")) {
        // ...
      }
    )

回调函数中的this指的是DOM元素。然而,这并不是D3的做法。应该将collapsed状态保存在与节点关联的data中,并根据其进行操作,而不是将状态保存在DOM元素的class中。


5
Musically_ut的解决方案是正确的,但只适用于最新的浏览器(例如,Safari 6.0.5及之前版本不起作用,其是发布于2013年6月5日)。
这里的棘手部分在于SVG DOM与HTML DOM不同。因此,您不能只使用classList.contains来支持旧版浏览器。(请参见SVG和HTML之间的基本jsfiddle比较
这是一个[稍微不那么美观]的版本,可与旧版浏览器一起使用。(jsfiddle
g.append("circle")
    .classed("collapse", true)
    .attr("cx", 50)
    .attr("cy", 50)
    .attr("r", radius * 0.4 - 10)
    .attr("fill", 'black')
    .on('click', function(d){
        this.setAttribute('class', '');
        // or if your element has other classnames as well
        // scan the class names, remove the "collapse" from it and push the new string into class.
        //if(this.className.baseVal.indexOf('collapse')>=0){ … }
    }
   );

1
尝试一下这个,虽然它太简单了:

enter code hereg.append("circle")
.classed("collapse", true)
.attr("cx", 0)
.attr("cy", 0)
.attr("r", radius * 0.4 - 10)
.attr("fill", color(radius * 0.4 - 10))
.on("click", (d)) {

  var this_ = d3.select(this);

    if(this_.select(".collapse").attr("visibility") == "visible") {

      this_.select(".collapse").attr("visibility", "hidden");

    } else {

      this_.select(".collapse").attr("visibility", "visible");

    }

});

1

问题中的代码看起来更像是CoffeeScript而不是纯JavaScript。如果是这种情况,那么使用d3.js的方法应该是:

.on "click", ->
  d3.select(this).classed("collapse", false) unless d3.select(this).select(".collapse").empty()

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