Bootstrap 5 modal 關閉彈窗跳出失焦警告

最近開發時發現關閉modal彈窗會跳出一個警告

Blocked aria-hidden on an element because its descendant retained focus. The focus must not be hidden from assistive technology users. Avoid using aria-hidden on a focused element or its ancestor. Consider using the inert attribute instead, which will also prevent focus. For more details, see the aria-hidden section of the WAI-ARIA specification at https://w3c.github.io/aria/#aria-hidden.
Element with focus: <button.btn-close>
Ancestor with aria-hidden: <div.modal fade#addCartModal> 

雖然好像不影響功能,但看了有點啊雜,翻譯一下好像是關閉彈窗後,要把焦點聚集回到按鈕上,不能直接隱藏,會影響「輔助技術使用者」,我猜應該是盲人輔助之類的,應該啦!不是很確定。

那解決辦法是建議用inert 屬性取代,但我發現用了就關不了視窗了,所以問了ChatGpt,他的解法有些不太正確,有些不太符合我的架構,例如按關閉後,聚焦回按鈕上,但我用Vue大多都把彈窗抽出來當Component用了,要想辦法聚焦回按鈕也可以,但就有點麻煩,需要所有父子組件都處理

所以我試了半天找到個解法如下

onMounted(() => {
  var modalEl = document.getElementById(props.elementId)
  // 加入以下
  modalEl.addEventListener('hide.bs.modal', () => {
    document.activeElement.blur();
  })
})

看起來應該就是關閉彈窗後,模糊焦點就可以了,就沒警告了,如有其他更好辦法,或我哪裡理解錯誤歡迎留言。

Leave a Reply

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *