如何将aria属性设置为highcharts工具提示

时间:2018-04-03 14:55:35

标签: javascript highcharts wai-aria

我有一个用自定义格式化工具提示的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);
        }
    }
}

我的问题是:我该如何清理它?必须有一种更有效的方式来编写这个函数。

1 个答案:

答案 0 :(得分:1)

如果您只想获得一个元素,请使用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);

要保存少量字符并希望长字符串更清晰,您可以使用template literals代替链接'…' + … + '…'

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);
        }
    }
}