Joe*_*ito 4 javascript jquery svg d3.js
我希望在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
)
Run Code Online (Sandbox Code Playgroud)
您可以使用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')
}
)
Run Code Online (Sandbox Code Playgroud)
或者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")) {
// ...
}
)
Run Code Online (Sandbox Code Playgroud)
在this
该回调里面指的DOM元素.然而,这并不是D3-isque的做事方式.应该将collapsed
状态保存在data
与节点关联的状态上并对其进行操作,而不是将状态保存class
在DOM元素中.
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){ … }
}
);
Run Code Online (Sandbox Code Playgroud)