class LiveStats extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = `
<div aria-live="polite" id="co2-output">CO₂ Saved: 10kg</div>
`;
}
updateCO2(newValue) {
const output = this.shadowRoot.getElementById("co2-output");
output.textContent = `CO₂ Saved: ${newValue}kg`;
}
}
customElements.define("live-stats", LiveStats);
i我期望呼叫
updateCO2(15)
我还尝试强制反流:
output.textContent = "";
setTimeout(() => {
output.textContent = `CO₂ Saved: ${newValue}kg`;
}, 10);
但这并不能可靠。
是Shadow dom内部的ARIA LIVE区域不可靠,或者是否有另一种技术来确保屏幕读取器始终读取动态更新?update:以下是一些虚拟代码。该页面只有一个单个Web组件(实时stat),其中一个简单的计数器每3秒更新一次。文本“更新:0”是一个占位符 - 它不代表现实世界数据。该页面无法连接到后端,API或外部数据库。如果有人可以解决这个问题,以找出为什么某些屏幕阅读器在Shadow dom内部进行实时更新而挣扎,因为他们并不总是检测到包封的组件内的更改。
<html lang="en"> <head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Stats Web Component</title> </head> <body>
<live-stats></live-stats>
<script>
class LiveStats extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = `
<div aria-live="polite" aria-atomic="true" id="counter">Updates: 0</div>
`;
this.count = 0;
}
updateCount() {
const counter = this.shadowRoot.getElementById("counter");
// Force DOM mutation to trigger screen reader announcement
counter.textContent = '\u2060'; // Invisible character
setTimeout(() => {
counter.textContent = `Updates: ${++this.count}`;
}, 50);
}
}
customElements.define("live-stats", LiveStats);
// Instantiate the component and update every 3 seconds
const stats = document.querySelector("live-stats");
setInterval(() => stats.updateCount(), 3000);
</script>
</body> </html>
i使用NVDA V2024.2.35031和Chrome V134.0.6998.89尝试了虚拟代码,并且一切都起作用了,似乎您的问题是由于浏览器或屏幕读取器问题所致。正如您在评论中所说的那样,问题是由于浏览器已过时。