d3 javascript alternate colors on click

前端 未结 3 1855
眼角桃花
眼角桃花 2021-01-04 09:55

I\'m just starting playing around with d3, and was wondering how you could alternate the colors of a element upon clicking it.

This fiddle changes the color of the

相关标签:
3条回答
  • 2021-01-04 10:06

    Make yourself a toggle function and pass it into the click: 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);
        }
    })();
    
    0 讨论(0)
  • 2021-01-04 10:14

    This also worked, albeit in a jankier fashion. . .

    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]);});
    
    0 讨论(0)
  • 2021-01-04 10:19

    EDIT: Does not work in Chrome, works in FF. The problem is in the fill atributte:

    this.style.fill
    

    Chrome change "white" by "#FFFFFF".

    By the way, the clearer solution should be toggling the class.

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

    See http://jsfiddle.net/kUZuW/

    0 讨论(0)
提交回复
热议问题