2012-06-07 10 views
10

私はd3で遊んでいます。クリックするとどのように要素の色を交互に変えることができますか?d3 javascriptの代わりにクリックすると

このフィドルは、それをクリックした円の色を変更しますが、再度クリックすると色が白くなるようにしたいと考えています。

現在のコード:

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

答えて

17

自身トグル機能作成し、クリックにそれを渡します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

感謝を参照してください!それは素晴らしい作品です。 – reptilicus

+0

@ user1443118問題はありません^ _^ – Neal

+0

@ user1443118私はライブラリーのないサンプルを作成しました:-P http://jsfiddle.net/maniator/WMUQA/ – Neal

1

これも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

EDIT:Chromeでは動作しません.FFFで動作します。問題は、塗りつぶしの問題です:

this.style.fill 

クロムの変更は "白"で "#FFFFFF"です。

ところで、明確な解決策は、クラスを切り替える必要があります。

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

http://jsfiddle.net/kUZuW/

+0

それはフィドルが働きません:-P – Neal

+0

興味深いことに、FireFox Chromeでは使用できません。 実際には、Chromeではthis.style.fillが#ffffffを返しますが、FFでは "white"が返されます – crispamares

+0

Hehe私はまったくライブラリを持たないモックアップを作成しました:http://jsfiddle.net/maniator/WMUQA/ :-P – Neal

関連する問題