【发布时间】:2020-09-17 09:24:44
【问题描述】:
免责声明:我知道它不是有效的 HTML。我想了解为什么不允许这样做?
W3C 建议像button 或a 这样的交互元素不得包含另一个交互元素。
我可以找到很多提到此规则和一些解决方法的资源,还有一些与此规则如何影响可访问性和屏幕阅读器相关的资源,但几乎所有这些资源都提到这是一项要求,但没有解释原因。
https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html
https://codepen.io/vloux/pen/wXGyOv
Nesting <a> inside <button> doesn't work in Firefox
https://github.com/dequelabs/axe-core/issues/601
我真的无法解释为什么不允许这样做?它会导致任何可用性问题吗?
这是一个相关的问题: Why should interactive element not be used within an anchor?
接受的答案令人满意,但不足以使此规则成为要求。使用适当的事件处理可以避免所描述的情况。
另外,如果嵌套的交互内容是无效的,我们怎么会有这样的东西:
一张整体可点击的卡片,里面还有一个可点击的辅助 CTA。 我知道一种解决方法是在卡内有一个主要和次要 CTA,但上述内容是否也应该被允许?
这是一个小提琴: https://jsfiddle.net/t9qbwas5/2/
<button type="button" class="card">
The card itself is the primary CTA.
<br/>
<br/>
some important content to read through.
some important content to read through.
some important content to read through.
<div class="cta">
Secondary CTA
</div>
</button>
.cta {
padding: 4px;
background: #00a9a9;
color: white;
width: 80px;
margin: auto;
margin-top: 8px;
margin-bottom: 8px;
}
.card {
width: 200px;
display: flex;
flex-direction: column;
justify-content: center;
text-align: center;
}
在上面的示例中,我通过在按钮内使用可点击的 div 来实现这一点,但这不是语义(?)和功能方面的,它是另一个内部的交互式元素。我试图理解,即使我使用这种解决方法,嵌套交互式元素从根本上来说是错误的吗?这是一种糟糕的设计/可用性实践吗?
【问题讨论】:
标签: html accessibility wai-aria semantic-markup