2012-06-07 21 views
10

Estoy empezando a jugar con d3 y me preguntaba cómo podría alternar los colores de un elemento al hacer clic en él.d3 javascript colores alternativos al hacer clic

Este violín cambia el color del círculo haciendo clic en él, pero luego me gustaría que el color vuelva a ser blanco después de hacer clic de nuevo.

Código actual:

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

Respuesta

17

Hazte una función de activación y pasarlo en el clic: 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

Gracias! Eso funciona genial – reptilicus

+0

@ user1443118 no hay problema^_^ – Neal

+0

@ user1443118 Acabo de hacer un ejemplo sin bibliotecas en absoluto :-P http://jsfiddle.net/maniator/WMUQA/ – Neal

1

Esto también trabajó, aunque de forma jankier. . .

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

EDITAR: No funciona en Chrome, funciona en FF. El problema está en el relleno atributte:

this.style.fill 

Cambio de cromo "blanco" por "#FFFFFF".

Por cierto, la solución más clara debería ser alternar la clase.

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

Ver http://jsfiddle.net/kUZuW/

+0

Ese violín no funciona :-P – Neal

+0

Interesante, funciona en Firefox , pero no en Chrome En realidad, en Chrome, this.style.fill devuelve #ffffff mientras que en FF devuelve "blanco" – crispamares

+0

Hehe Acabo de hacer una maqueta sin ninguna biblioteca: http://jsfiddle.net/maniator/WMUQA/ :-P – Neal