如何在鼠标悬停在条形图上时显示标签

How to show label when mouse over bar

本文关键字:显示 标签 悬停 鼠标 条形图      更新时间:2023-09-26

我用chartist.js.制作了一个条形图

现在我想在酒吧里增加一些听力活动。

当鼠标悬停在条形图上时,如何让标签显示?

您有两个选项-


选项1


有一个工具提示插件,你可以使用。你可以在这里找到它-https://github.com/Globegitter/chartist-plugin-tooltip

一旦你添加了CSS和JS文件,你就应该能够调用这样的插件-Chartist.plugins.tooltip()

以下是他们插件页面上的一个例子-

var chart = new Chartist.Line('.ct-chart', {
  labels: [1, 2, 3],
  series: [
    [
      {meta: 'description', value: 1 },
      {meta: 'description', value: 5},
      {meta: 'description', value: 3}
    ],
    [
      {meta: 'other description', value: 2},
      {meta: 'other description', value: 4},
      {meta: 'other description', value: 2}
    ]
  ]
}, {
  low: 0,
  high: 8,
  fullWidth: true,
  plugins: [
    Chartist.plugins.tooltip()
  ]
});

这将是一个更容易、更好的选择。


选项2


如果你想自己做一些事情,你可以在draw事件的回调-上绑定mouseovermouseout事件

var data = {
  labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'],
  series: [
    [1, 2, 4, 8, 6, -2, -1, -4, -6, -2]
  ]
};
var options = {
  high: 10,
  low: -10,
  axisX: {
    labelInterpolationFnc: function(value, index) {
      return index % 2 === 0 ? value : null;
    }
  }
};
var chart = new Chartist.Bar('.ct-chart', data, options);
// Based on ty's comment
chart.on('created', function(bar) {
  $('.ct-bar').on('mouseover', function() {
    $('#tooltip').html('<b>Selected Value: </b>' + $(this).attr('ct:value'));
  });
  $('.ct-bar').on('mouseout', function() {
    $('#tooltip').html('<b>Selected Value:</b>');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/chartist.js/0.9.5/chartist.min.js"></script>
<link href="https://cdn.jsdelivr.net/chartist.js/0.9.5/chartist.min.css" rel="stylesheet" />
<div id="tooltip"><b>Selected Value:</b>
</div>
<div class="ct-chart"></div>

更新:根据ty的注释

更新代码