d3 javascript点击时的交替颜色 [英] d3 javascript alternate colors on click

查看:985
本文介绍了d3 javascript点击时的交替颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始玩d3,并想知道如何可以交替的元素的颜色点击它。

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 circle clicking it, but then I'd like to get the color back to being white after clicking again.

当前代码:

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


推荐答案

让自己成为切换函数, : http://jsfiddle.net/maniator/Bvmgm/6/

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

这篇关于d3 javascript点击时的交替颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆