简体   繁体   English

尽管隐藏了 div,但仍宣布 aria-live 文本更改

[英]Announce aria-live text change despite div being hidden

I have a div with an icon and a message which is hidden unless someone mouses over it, that does an action when clicked.我有一个带有图标的 div 和一条消息,除非有人将鼠标悬停在它上面,否则它会在单击时执行操作。

For sighted users, the icon switches to a check mark when clicked, and the message is changed when the icon is hovered over.对于视力正常的用户,单击该图标时会切换为复选标记,并且当该图标悬停在其上方时会更改消息。 For users that use the tab button however, the message isn't displayed.但是,对于使用选项卡按钮的用户,不会显示该消息。

The div with the message is an aria-live region, but since it is hidden, the screen reader will not announce the new message.带有消息的 div 是一个 aria-live 区域,但由于它是隐藏的,屏幕阅读器不会宣布新消息。 Is there a way to announce the message despite the region being hidden?尽管区域被隐藏,有没有办法宣布消息?

The short answer is no.最简洁的答案是不。 an aria-live region must be visible if you want its content changes to be announced.如果您希望宣布其内容更改,则必须显示 aria-live 区域。

You may read this question where I give a small trick: show the element a few seconds, long enough to let the screen reader read the message, and then hide again.你可能会读到这个问题,我给出了一个小技巧:显示元素几秒钟,时间足够让屏幕阅读器阅读消息,然后再次隐藏。 However you must show the message at least for 3-5 seconds because some screen readers cut of before the end if you hide the element while it is still being spoken.但是,您必须至少显示消息 3-5 秒,因为如果您在仍在朗读该元素时隐藏该元素,则某些屏幕阅读器会在结束前切掉。

IF showing the message for that long is unacceptable, you can still put it off-screen, by using a little CSS like below.如果显示消息那么长时间是不可接受的,您仍然可以通过使用如下所示的一些 CSS 将其置于屏幕外。 Note that many frameworks already have classes like .visually-hidden, .sr-only, etc. with a similar code.请注意,许多框架已经具有类似 .visually-hidden、.sr-only 等具有类似代码的类。 If you are using one of them, use what they define.如果您正在使用其中之一,请使用它们定义的内容。

.visually-hidden {
top:0;
left:-2px;
width:1px;
height:1px;
position:absolute;
overflow:hidden;
}

``` ``

I've found a better way to handle this issue.我找到了一个更好的方法来处理这个问题。 First you'll have to always set your live element visibile in DOM, not UI, and after that, you'll need to update the textContent , or innerHTML ;首先,您必须始终在 DOM 中设置活动元素可见,而不是在 UI 中,然后,您需要更新textContentinnerHTML next step, just setTimeout for a couple of milliseconds (100ms in my case) or more, and after that just clear the contents inside.下一步,只需setTimeout几毫秒(在我的情况下为 100 毫秒)或更长时间,然后清除里面的内容。 In this way the screen reader will still read the previous message entirely.通过这种方式,屏幕阅读器仍将完整地阅读上一条消息。 You can also clearTimeout if new messages has to be appended in the meantime.如果在此期间必须附加新消息,您还可以clearTimeout

example:例子:

function updateLiveRegion(message) {
    const elem = document.getElementById("my-id");
    elem.textContent = message;
    clearTimeout(myTimeout);
    myTimeout = setTimeout(() => {
        elem.textContent = "";
    } , 1000);
}

updateLiveRegion("my message");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM