google-visualization-tooltip 如何计算 style 的 left 和 top 值?示例-在调试时我可以看到:-
<div class="google-visualization-tooltip" style="width: 1px; height: 0px; left: 453.25px; top: 44.91px;"</div>
我如何相对计算它,以便工具提示显示在顶部并与悬停的点居中对齐,而与元素的宽度无关?
google-visualization-tooltip 如何计算 style 的 left 和 top 值?示例-在调试时我可以看到:-
<div class="google-visualization-tooltip" style="width: 1px; height: 0px; left: 453.25px; top: 44.91px;"</div>
我如何相对计算它,以便工具提示显示在顶部并与悬停的点居中对齐,而与元素的宽度无关?
'corechart'
包中的大多数图表
都有获取各种图表元素位置的 方法。
首先,获取图表的布局界面...
var chartLayout = chart.getChartLayoutInterface();
布局界面有方法 -->getBoundingBox(id)
其中id
是图表元素的字符串 id。
要查找点的位置,请将此格式用于id
--> point#series#row
--point#0#0
我们可以使用图表事件onmouseover
来了解某个点何时被悬停,
并显示工具提示。
该onmouseover
事件发送一个参数,其中包含数据表中的行和列,
即悬停点。
因此,我们可以获取布局、找到点并定位工具提示。
google.visualization.events.addListener(chart, 'onmouseover', function (sender) {
// ensure point is hovered
if (sender.row !== null) {
var padding = 16;
var chartLayout = chart.getChartLayoutInterface();
var pointBounds = chartLayout.getBoundingBox('point#' + (sender.column - 1) + '#' + sender.row);
var tooltip = chart.getContainer().getElementsByClassName('google-visualization-tooltip');
if (tooltip.length > 0) {
var tooltipBounds = tooltip[0].getBoundingClientRect();
tooltip[0].style.top = (pointBounds.top - tooltipBounds.height - padding) + 'px';
tooltip[0].style.left = ((pointBounds.left + (pointBounds.width / 2)) - (tooltipBounds.width / 2)) + 'px';
}
}
});
请参阅以下工作片段...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable({
"cols": [
{"label": "x", "type": "number"},
{"label": "y", "type": "number"}
],
"rows": [
{"c":[{"v": 2015}, {"v": 1}]},
{"c":[{"v": 2016}, {"v": 2}]},
{"c":[{"v": 2017}, {"v": 3}]},
{"c":[{"v": 2018}, {"v": 4}]},
{"c":[{"v": 2019}, {"v": 5}]},
{"c":[{"v": 2020}, {"v": 6}]}
]
});
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'onmouseover', function (sender) {
// ensure point is hovered
if (sender.row !== null) {
var padding = 16;
var chartLayout = chart.getChartLayoutInterface();
var pointBounds = chartLayout.getBoundingBox('point#' + (sender.column - 1) + '#' + sender.row);
var tooltip = chart.getContainer().getElementsByClassName('google-visualization-tooltip');
if (tooltip.length > 0) {
var tooltipBounds = tooltip[0].getBoundingClientRect();
tooltip[0].style.top = (pointBounds.top - tooltipBounds.height - padding) + 'px';
tooltip[0].style.left = ((pointBounds.left + (pointBounds.width / 2)) - (tooltipBounds.width / 2)) + 'px';
}
}
});
var options = {
chartArea: {
bottom: 32,
left: 32,
right: 32,
top: 48,
width: '100%',
height: '100%'
},
hAxis: {
format: '0',
ticks: data.getDistinctValues(0)
},
legend: {
position: 'top'
},
pointSize: 4,
tooltip: {
isHtml: true,
trigger: 'both'
}
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>