[英]How to set aria attributes to highcharts tooltips
我有一個用自定義格式的工具提示在React應用程序中編寫的圖表(Highcharts); 但是,屏幕閱讀器在“標記”這些要點時不會宣布工具提示內容。
我寫了一些JavaScript來解決我的問題,並在mouseOut上宣布了工具提示,因為它們應該在沒有在DOM中創建不必要元素的情況下被宣布。
point: {
events: {
mouseOut: function () {
let ariaText = this.category + ', Projected Savings: $ ' + this.projectedSavingsFormatted + ', Target Savings: ' + targetSavingsFormatted + ', Time to Achieve: ' + this.timeToAcheive + ' months';
let tooltips = document.querySelectorAll('div.highcharts-tooltip')[0];
tooltips.getElementsByTagName('span')[0].setAttribute('role', 'tooltip');
tooltips.getElementsByTagName('span')[0].setAttribute('aria-live', 'assertive');
tooltips.getElementsByTagName('span')[0].setAttribute('aria-label', ariaText);
}
}
}
我的問題是:我該如何清理? 必須有一種更有效的方式來編寫此功能。
如果只想獲取單個元素,請使用querySelector(…)
而不是querySelectorAll(…)[0]
:
let tooltips = document.querySelectorAll('div.highcharts-tooltip')[0];
// becomes:
let tooltips = document.querySelector('div.highcharts-tooltip');
但是,根據您的代碼,似乎沒有必要選擇div
–如果您只想要第一個span
,則立即選擇它,而無需存儲父節點:
let tooltip = document.querySelector('div.highcharts-tooltip span');
tooltip.setAttribute('role', 'tooltip');
tooltip.setAttribute('aria-live', 'assertive');
tooltip.setAttribute('aria-label', ariaText);
為了節省一些字符並希望使長字符串更清晰,您可以使用模板文字,而不是鏈接'…' + … + '…'
:
let ariaText = this.category + ', Projected Savings: $ ' + this.projectedSavingsFormatted + ', Target Savings: ' + targetSavingsFormatted + ', Time to Achieve: ' + this.timeToAcheive + ' months';
// becomes:
let ariaText = `${this.category}, Projected Savings: $ ${this.projectedSavingsFormatted}, Target Savings: ${targetSavingsFormatted}, Time to Achieve: ${this.timeToAcheive} months`;
// notice the backticks (``) instead of quotes ('')
因此,您的功能可能變為:
point: {
events: {
mouseOut: function () {
let ariaText = `${this.category}, Projected Savings: $ ${this.projectedSavingsFormatted}, Target Savings: ${targetSavingsFormatted}, Time to Achieve: ${this.timeToAcheive} months`;
let tooltip = document.querySelector('div.highcharts-tooltip span');
tooltip.setAttribute('role', 'tooltip');
tooltip.setAttribute('aria-live', 'assertive');
tooltip.setAttribute('aria-label', ariaText);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.