单击时 d3 javascript 替代颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10939082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:39:40  来源:igfitidea点击:

d3 javascript alternate colors on click

javascriptd3.js

提问by reptilicus

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

我刚开始玩 d3,想知道如何在单击元素时改变元素的颜色。

This fiddle changes the color of the circle clicking it, but then I'd like to get the color back to being white after clicking again.

这个小提琴改变了点击它的圆圈的颜色,但我想再次点击后将颜色恢复为白色。

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

回答by Naftali aka Neal

Make yourself a toggle function and pass it into the click: http://jsfiddle.net/maniator/Bvmgm/6/

使自己成为一个切换功能并将其传递给点击: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);
    }
})();

回答by reptilicus

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

回答by crispamares

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

编辑:不适用于 Chrome,适用于 FF。问题在于填充属性:

this.style.fill

Chrome change "white" by "#FFFFFF".

Chrome 将“白色”更改为“#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/

http://jsfiddle.net/kUZuW/