在chart.js折线图上使x轴上的月份可点击 [英] Make months on x-axis clickable on chart.js line chart

查看:20
本文介绍了在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轴上的月份可点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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