d3.js使轴刻度可点击 [英] d3.js make axis ticks clickable

查看:284
本文介绍了d3.js使轴刻度可点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有人知道一种使轴上的标签可点击的方法。现在我的轴生成如下:

I was wondering if anyone knows a way to make the labels on the axis clickable. Right now my axis are generated as follows:

    // Add an x-axis with label.
    svg.append("g")
        .attr("id", "xaxis")
        .attr("class", "x axis")
        .attr("transform", "translate(" + (margin.left + margin.left_padding) + "," + height + ")")
        .attr("text_anchor", "top")
        .call(d3.svg.axis().scale(x).orient("bottom"))
        .selectAll("text")
            .style("text-anchor", "end")
            .attr("font-size", "12")
            .attr("dx", "-.8em")
            .attr("dy", ".15em")
            .attr("transform", function(d) {
                return "rotate(-45)"
            })


    // Add a y-axis with label.
    svg.append("g")
        .attr("id", "yaxis")
        .attr("class", "y axis")
        .attr("transform", "translate(" + (margin.left + margin.left_padding) + "," + 0 + ")")
        .attr("text-anchor", "right")
        .call(d3.svg.axis().scale(y).orient("left"))
        .selectAll("text")
           .attr("font-size", "12")

    }



我想知道如何使每个轴上的数字/标签有一个onclick事件。

I'm wondering how to make it possible for each number/label on the axis have an onclick event.

推荐答案

您可以用d3选择它们,然后绑定一个函数 .on('click',function)

You can select them with d3 and then bind a function to them with .on('click', function)

对于你的代码, p>

For your code, this would look something like this:

d3.select('#xaxis')
    .selectAll('.tick.major')
    .on('click',clickMe)

function clickMe(){alert("I've been clicked!")}

请注意,这将选择整个刻度,而不只是文本,因为 .tick.major 是组的类

Note that this will select the entire tick, not just the text, since .tick.major is the class of the group that contains both the tick label (the text) and the tick itself (an SVG line).

也可以使用 d 作为函数中的参数,你正在调用你的ticks。如果这样做, d 将包含tick的值。例如,以下将发送包含每个tick值的alert:

You can also use d as an argument in the function you are calling on your ticks. If you do so, d will contain the value of the tick. For example, the following would send an alert containing each tick value:

d3.select('#xaxis')
    .selectAll('.tick.major')
    .on('click',clickMe)

function clickMe(d){alert(d)}


$ b > .tick.major 如果只有主要的刻度有主要类。

Note that you can probably call .major instead of .tick.major if nothing but the major ticks has the major class.

这篇关于d3.js使轴刻度可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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