gpt4 book ai didi

javascript - d3.js 使轴刻度可点击

转载 作者:数据小太阳 更新时间:2023-10-29 04:29:05 25 4
gpt4 key购买 nike

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

    // 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 事件。

最佳答案

您可以使用 d3 选择它们,然后使用 .on('click', function) 将函数绑定(bind)到它们

对于您的代码,这看起来像这样:

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

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

请注意,这将选择整个刻度,而不仅仅是文本,因为 .tick.major 是包含刻度标签(文本)和刻度本身的组的类(一条 SVG 线)。

您还可以使用 d 作为您在报价上调用的函数中的参数。如果这样做,d 将包含刻度的值。例如,以下将发送包含每个刻度值的警报:

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

function clickMe(d){alert(d)}

请注意,如果只有主要刻度线具有 major 类,您可以调用 .major 而不是 .tick.major

关于javascript - d3.js 使轴刻度可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17282801/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com