点击时使用D3 JavaScript交替颜色

13

我刚开始尝试使用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");});
3个回答

20

制作一个切换函数并将其传递给点击事件: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);
    }
})();

@user1443118,我刚刚做了一个没有任何库的示例 :-P http://jsfiddle.net/maniator/WMUQA/ - Naftali

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]);});

1

编辑:在Chrome中无法工作,但在FF中可以。问题出在fill属性上:

this.style.fill

Chrome将“白色”更改为“#FFFFFF”。

顺便说一下,更清晰的解决方案应该是切换类。

.on("click", function(){var nextColor = this.style.fill == "white" ? "magenta" : "white";
        d3.select(this).style("fill", nextColor);});

请查看http://jsfiddle.net/kUZuW/


有趣的是,在 FireFox 上可以工作,但在 Chrome 上卻不行。 實際上,在 Chrome 中,this.style.fill 返回 #ffffff,而在 FF 中返回 "white"。 - crispamares
哈哈,我刚刚做了一个没有任何库的模型:http://jsfiddle.net/maniator/WMUQA/ :-P - Naftali

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