2012-06-07 3 views
10

Ich fange gerade an, mit d3 herumzuspielen, und habe mich gefragt, wie man die Farben eines Elements beim Anklicken wechseln könnte.d3 javascript alternate colours on click

Diese Geige ändert die Farbe des Kreises, der darauf klickt, aber dann möchte ich die Farbe wieder weiß machen, nachdem ich wieder geklickt habe.

Aktuelle Code:

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

Antwort

17

sich eine Umschaltfunktion und nutzen es in den Klick passieren: 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

Dank! Das funktioniert großartig. – reptilicus

+0

@ user1443118 kein Problem^_^ – Neal

+0

@ user1443118 Ich habe nur ein Beispiel ohne Bibliotheken überhaupt gemacht :-P http://jsfiddle.net/maniator/WMUQA/ – Neal

1

Das funktionierte auch, wenn auch in jankier Art und Weise. . .

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

EDIT: Funktioniert nicht in Chrome, funktioniert in FF. Das Problem ist in der Füllung atributte:

this.style.fill 

Chrom ändern "weiß" von "#FFFFFF".

Übrigens sollte die klarere Lösung die Klasse wechseln.

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

Siehe http://jsfiddle.net/kUZuW/

+0

Diese Geige funktioniert nicht :-P – Neal

+0

Interessant, funktioniert auf FireFox , aber nicht auf Chrome. Tatsächlich gibt this.style.fill in Chrome #ffffff zurück, während in FF "white" zurückgegeben wird. – crispamares

+0

Hehe Ich habe gerade ein Mockup ohne Bibliotheken erstellt: http://jsfiddle.net/maniator/WMUQA/ :-P – Neal