如何在鼠标悬停在栏上时显示标签 [英] How to show label when mouse over bar

查看:174
本文介绍了如何在鼠标悬停在栏上时显示标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I made a Bar chart by chartist.js.

现在我想在栏上添加一些听力事件。

Now I want to add some listening event on the bars.

如何在鼠标悬停在栏上时让标签显示?

How can I do to let label show up when mouse over the bar?

推荐答案

您有2个选项 -


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

There is a tooltip plugin that you could use. You can find it here - https://github.com/Globegitter/chartist-plugin-tooltip

添加CSS和JS文件后,您应该可以像这样调用插件 - Chartist.plugins.tooltip( )

Once you add the CSS and JS files, you should be able to call the plugin like this - Chartist.plugins.tooltip()

这是他们的插件页面 -

Here is an example from their Plugins page -

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()
  ]
});

这将是更简单,更好的选择。

This will be the easier and the better option.


如果您想自己做某事,可以绑定鼠标悬停 mouseout 事件抽奖事件的回调 -

If you want to do something by yourself, you can bind mouseover and mouseout events on draw event's callback -

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的代码评论

UPDATE: Updated the code as per ty's comment

这篇关于如何在鼠标悬停在栏上时显示标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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