如何在 HTML 中正确禁用按钮?

问题描述 投票:0回答:1

可以通过设置

<button>
属性来禁用
disabled
元素
,例如使用

document.querySelector("button").disabled = true;

但是,这会产生一些“不利的可用性影响”,例如导致按钮失去焦点并无法通过键盘导航进行访问。有些用户会看到按钮被禁用的视觉提示,例如因为表单中可能缺少某些内容。对于依赖键盘导航和屏幕阅读器的用户来说,获取此信息会困难得多。 禁用按钮的好方法是什么?

javascript html accessibility disabled-input
1个回答
0
投票

aria-disabled 属性

 来执行此操作:

/** * Adds eventListeners to the buttons. * Here, not the action is added but the guard. */ document.querySelectorAll("button").forEach(button => { button.addEventListener("click", actionGuard(action)) }); /** * This guard prevents the action if the button * is disabled or event handling was prevented. * @param {EventListener} action * @returns {EventListener} */ function actionGuard(action) { return (evt) => { if (evt.target?.ariaDisabled) evt.preventDefault(); else if (!evt.defaultPrevented) action(evt) } } /** * The action you want your button to perfom. * @type {EventListener} */ function action(evt) { console.log("Event callback triggered:", evt.type) }
button[aria-disabled="true"] {
  opacity: .65;
  cursor: not-allowed;
}
<button type="button">Enabled</button>
<button type="button" aria-disabled="true">Disabled</button>

基于

aria-disabled

属性,按钮的样式已更改,以便您仍然可以获得该按钮处于非活动状态的视觉提示。此外,只有当

aria-disabled
属性不为 true 并且事件尚未被阻止时,守卫才会允许执行该操作。
为了提高可用性,您可以考虑向此禁用按钮添加工具提示,告知用户该按钮被禁用的原因。添加工具提示时,请务必通过添加 

aria-live 元素

来帮助屏幕阅读器用户。

© www.soinside.com 2019 - 2024. All rights reserved.