如何在chartjs中以编程方式触发悬停 [英] How to trigger hover programmatically in chartjs

查看:26
本文介绍了如何在chartjs中以编程方式触发悬停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以编程方式在 ChartJs 中设置悬停效果我希望看到两种效果 hoverBorderWidthhoverBorderColor.我知道如何激活一些工具提示,但我无法应用悬停效果.例如,如果我有图表和一些外部链接,我可以触发 mouseover 事件到链接.我想在 ChartJs 中实现悬停效果,我该怎么做?

I want to set the hover effect in ChartJs programmatically i wish to see both effects hoverBorderWidth, and hoverBorderColor. I know how to activate some tooltips, but I can't apply hover effects. For example, if I have chart and some links outside, I can trigger mouseover events to links. I want to have the hover effect in ChartJs, how can i do this?

感谢您的回答.

推荐答案

Chart.js 侦听 mousemove 事件并检查数据点是否位于 x/y 坐标处.如果是这样,它会触发该点的悬停"行为.

Chart.js listens for mousemove events and checks if a datapoint is at the x/y coordinates. If so, it triggers the 'hover' behaviour for that point.

借鉴Chart.js工具提示测试代码,我编写了下面的代码片段来演示访问正确的属性和触发事件.

Borrowing from the Chart.js tooltips test code, I wrote the snippet below to demonstrate accessing the correct properties and triggering an event.

let c = new Chart($('#chart'), {
  type: 'doughnut',
  data: {
    labels: ['a', 'b', 'c', 'd'],
    datasets: [{
      data: [1, 2, 4, 8],
      backgroundColor: ['red', 'blue', 'green', 'orange']
    }]
  },
  options: {
    maintainAspectRatio: false
  }
});
$('#a').on('click', function() { t(0); });
$('#b').on('click', function() { t(1); });
$('#c').on('click', function() { t(2); });
$('#d').on('click', function() { t(3); });

function t(idx) {
  var meta = c.getDatasetMeta(0),
    rect = c.canvas.getBoundingClientRect(),
    point = meta.data[idx].getCenterPoint(),
    evt = new MouseEvent('mousemove', {
      clientX: rect.left + point.x,
      clientY: rect.top + point.y
    }),
    node = c.canvas;
  node.dispatchEvent(evt);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.min.js"></script>
<button id="a">Hover a</button>
<button id="b">Hover b</button>
<button id="c">Hover c</button>
<button id="d">Hover d</button>
<canvas id="chart"></canvas>

这篇关于如何在chartjs中以编程方式触发悬停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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