我刚刚开始玩d3,并且想知道如何在点击它时交替元素的颜色。
这个小提琴改变了点击它的圆圈的颜色,但是我想再次点击后再将颜色恢复为白色。
当前代码:
var sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 100)
.attr("height", 100);
sampleSVG.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 50)
.on("click", function(){d3.select(this).style("fill", "magenta");});
答案 0 :(得分:19)
让自己成为切换功能并将其传递到点击:http://jsfiddle.net/maniator/Bvmgm/6/
var toggleColor = (function(){
var currentColor = "white";
return function(){
currentColor = currentColor == "white" ? "magenta" : "white";
d3.select(this).style("fill", currentColor);
}
})();
答案 1 :(得分:3)
这也很有效,尽管是一种笨拙的方式。 。 。
var PointColors = ['white', 'magenta']
var sampleSVG = d3.select("#viz")
.append("svg")
.attr("width", 100)
.attr("height", 100);
sampleSVG.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", 40)
.attr("cx", 50)
.attr("cy", 50)
.on("click", function(){
PointColors = [PointColors[1], PointColors[0]]
d3.select(this).style("fill", PointColors[0]);});
答案 2 :(得分:1)
编辑:在Chrome中不起作用,适用于FF。问题在于填充:
this.style.fill
Chrome通过“#FFFFFF”更改“白色”。
顺便说一句,更清晰的解决方案应该是切换课程。
.on("click", function(){var nextColor = this.style.fill == "white" ? "magenta" : "white";
d3.select(this).style("fill", nextColor);});