对于使用聚合物或只想使用纯 js 执行此操作的任何人,以下是如何管理将在加载时创建并在每次图表更新时重绘的对象:
http://jsfiddle.net/57xw879k/1/
这样做的好处是它被添加到图表对象中,因此您不依赖 DOM 或任何特定的访问它的方法。
如果您想在不同时间执行操作, http://api.highcharts.com/highcharts/chart.events也值得一读。
HTML:
<script src="https://code.highcharts.com/highcharts.js"></script>
<div id="container"></div>
<button id="remove">
Remove label
</button>
<button id="add">
Add label
</button>
JS:
const chart = Highcharts.chart('container', {
chart: {
events: {
render: function() {
handleLabel(this)
var label = this.renderer.label('The chart was just redrawn', 100, 120)
.attr({
fill: Highcharts.getOptions().colors[0],
padding: 10,
r: 5,
zIndex: 8
})
.css({
color: '#FFFFFF'
})
.add()
setTimeout(function () {
label.fadeOut()
}, 1000)
}
}
},
title: {text: 'Highcharts label actions'},
xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
})
function handleLabel(chart) {
if (chart.myLabel) {
chart.myLabel.destroy()
addLabel(chart)
} else {
addLabel(chart)
}
}
function addLabel(chart) {
var point = chart.series[0].points[8];
chart.myLabel = chart.renderer.label('Max observation', 270, 50, 'callout', point.plotX + chart.plotLeft, point.plotY + chart.plotTop)
.css({
color: '#FFFFFF'
})
.attr({
fill: 'rgba(0, 0, 0, 0.75)',
padding: 8,
r: 5,
zIndex: 6
})
.add()
}
function removeLabel(chart) {
!objectIsEmpty(chart.myLabel) && chart.myLabel && chart.myLabel.destroy()
}
function objectIsEmpty(obj) {
return Object.keys(obj).length === 0 && obj.constructor === Object
}
document.getElementById('remove').addEventListener('click', () => removeLabel(chart))
document.getElementById('add').addEventListener('click', () => addLabel(chart))