【问题标题】:How to show label when mouse over bar鼠标悬停在栏上时如何显示标签
【发布时间】:2023-03-06 15:05:01
【问题描述】:

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

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

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

【问题讨论】:

    标签: javascript chartist.js


    【解决方案1】:

    你有两个选择 -


    选项 1


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

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

    这是来自他们Plugins 页面的示例 -

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

    【讨论】:

    • 太棒了!这就是我想要的。
    • 我正在使用流星并尝试在折线图上使用您的代码...但是 console.log($(this).attr('ct:value')); undefined 有什么想法吗?
    • 不错的解决方案 Ashwin。是否可以标记红色水平条是什么?
    • 在选项 #2 中,您定义 addedEvents 但永远不会更改其值。这意味着,如果您绘制 50 个项目,您将最多将 50 个事件绑定到每个点!更清洁、更有效的方法是使用 chart.on('created', function() { ...},它只被调用一次,然后删除 addedEvents
    • @EthanWaldie 使用 element.GetAttribute("ct:value");停止到处使用 jquery。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-06
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多