Make months on x-axis clickable on chart.js line chart(在chart.js折线图上使x轴上的月份可点击)
问题描述
我正在使用 chart.js 创建折线图.我的 x 轴基于时间并显示月份.
每个月列"都应该是可点击/可选择的,但我找不到管理它的方法.getElementAtEvent()
之类的方法返回数据,因此我可以找出选择了哪个月份.但它们仅在用户单击某个点时才有效,而不是列"中的任何位置.
I'm creating a line chart with chart.js. My x-axis is time-based and displays months.
Each "month column" should be clickable/selectable, but I cannot find a way to manage this. Methods like getElementAtEvent()
return data, so I can find out which month is selected. But they only work if the user clicks right on a point, and not anywhere in the "column".
我该怎么做?还是已经有这个插件?
How can I do that? Or is there already a plugin for this?
推荐答案
我能够使用一个名为 .getValueForPixel()
的未记录的时间尺度原型方法来完成这个工作,它返回的尺度值被点击的比例区域.
I was able to get this working using an undocumented time scale prototype method called .getValueForPixel()
, which returns the scale value of the scale region that was clicked.
此方法返回一个用于生成刻度刻度标签的时刻对象,因此您可以在显示此值时使用为您的时间刻度配置的相同格式字符串(如果您希望它们在视觉上相等).我将它与通用 onClick
选项配置相结合property 为您想要做的事情提供了一种非常简单的方法.
This method returns a moment object that was used to generate the scale tick label, so you can use the same format string configured for your time scale when displaying this value (if you want them to be visually equal). I coupled this with the generic onClick
option config property for a pretty simple approach for what you are wanting to do.
这里是如何做到这一点.在您的 options
对象中,使用此函数添加 onClick
属性.
Here is how to do it. In your options
object, add an onClick
property using this function.
onClick: function(e) {
var xLabel = this.scales['x-axis-0'].getValueForPixel(e.x);
console.log(xLabel.format('MMM YYYY'));
alert("clicked x-axis area: " + xLabel.format('MMM YYYY'));
},
这里有一个 codepen 示例来查看它的实际效果.
Here is a codepen example to see it in action.
这篇关于在chart.js折线图上使x轴上的月份可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在chart.js折线图上使x轴上的月份可点击


基础教程推荐
- 如何在特定日期之前获取消息? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01