我有一个包含Google Chart Gauge和Google Chart Linechart的页面。 我想在折线图标题后面放置一个图标。 我使用以下代码执行此操作:
var e = $("text:contains('CHART TITLE')");
var off = e.offset();
$("#refreshIcon").css({
left: off.left + e.width() + 10,
top: off.top - e.height(),
position: "absolute",
'z-index': 999
});
线路图与仪表发生冲突。测试的场景:
1)仪表顶部,下面的折线图:错误的图标放置
2)顶部的折线图,下面的仪表:工作正常
3)禁用仪表绘图(只需在drawGauge()中执行返回):正常工作
有什么建议吗?小提琴是here
答案 0 :(得分:0)
使用position()
代替offset()
会给您top
,
相对于文档,而不是偏移父
另外,由于仪表图表会影响图像的位置,因此 在设置展示位置之前需要等到两个图表都完成绘图
请参阅以下工作代码段...
google.charts.load('current', {
callback: drawCharts,
packages: ['gauge', 'corechart']
});
function drawCharts() {
drawChart();
drawGauges();
}
function drawGauges() {
var data = google.visualization.arrayToDataTable([
['Label', 'Value'],
['Memory', 80],
['CPU', 55],
]);
var w = $(window).width();
var x = Math.floor(w * 0.3);
var h = $(window).height();
var y = Math.floor(h * 0.3);
var options = {
redFrom: 90,
redTo: 100,
yellowFrom: 75,
yellowTo: 90,
minorTicks: 5,
width: x,
height: y,
};
var chart = new google.visualization.Gauge(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', moveImage);
chart.draw(data, options);
}
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2004', 1000, 400],
['2005', 1170, 460],
['2006', 660, 1120],
['2007', 1030, 540]
]);
var options = {
title: 'CHART TITLE',
curveType: 'function',
legend: {
position: 'bottom'
}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
google.visualization.events.addListener(chart, 'ready', moveImage);
chart.draw(data, options);
}
function moveImage() {
var e = $("text:contains('CHART TITLE')");
var off = e.position();
$("#refreshIcon").css({
left: off.left + e.width() + 10,
top: off.top - e.height() + 10,
position: "absolute",
'z-index': 999
});
}
$(window).resize(drawCharts);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" type="text/css"/>
<i id="refreshIcon" class="fa fa-refresh" aria-hidden="true"></i>
<div class="container" id="container">
<div class="row">
<div id="chart_div"></div>
</div>
<div class="row" id="row1">
<div id="curve_chart">
</div>
</div>
</div>