我正在使用 node.js 和 Chartist.js 制作图表,并使用 jQuery 和 CSS 为点创建工具提示。
现在,问题是图表正在服务器中生成,并且始终具有与 Chartist.js 生成相同的根类 ct-chart
和相同的其他类。由于我的代码中有多个图表,因此当我将鼠标悬停在一个图表上的某个点上时,它会在所有图表上显示工具提示,而不仅仅是该图表本身。
我该如何解决这个问题?
这是我的代码:
var $tooltip = $('<div class="tooltip tooltip-hidden"></div>').appendTo($('.ct-chart'));
console.log($tooltip);
$(document).on('mouseenter', '.ct-point', function() {
var seriesName = $(this).closest('.ct-point').attr('ct:meta'),
value = $(this).attr('ct:value');
$tooltip.text(seriesName);
$tooltip.removeClass('tooltip-hidden');
});
$(document).on('mouseleave', '.ct-point', function() {
$tooltip.addClass('tooltip-hidden');
});
$(document).on('mousemove', '.ct-point', function(event) {
$tooltip.css({
left: event.offsetX - $tooltip.width() / 2,
top: event.offsetY - $tooltip.height() - 20
});
});
最佳答案
我认为发生的情况是 $tooltip
变量包含所有图表的 jquery 数组。因此,当您执行 $tooltip.removeClass('tooltip-hidden');
时,它会从所有这些中删除该类。
您需要一种方法来区分它们 - 我建议如下:
$(document).on('mouseenter', '.ct-point', function() {
var seriesName = $(this).closest('.ct-point').attr('ct:meta'),
value = $(this).attr('ct:value'),
index = $(this).index(); // get the index of the point
$tooltip.eq(index).text(seriesName);
$tooltip.eq(index).removeClass('tooltip-hidden'); // use the index to remove only one class
});
我还没有测试过这个,但我认为它应该有效。您必须将其应用到您的所有代码中。
我构建了这个小测试,以表明当您使用“appendTo”时,该变量将填充您所定位的所有元素。 https://jsfiddle.net/wvLy2enm/
您也应该在控制台日志中看到这一点。
关于javascript - 将鼠标悬停在图表上的某个点上时显示所有图表的工具提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50261182/