首页 > 解决方案 > HTML 验证:为什么将交互式元素放在交互式元素中是无效的?

问题描述

免责声明:我了解它不是有效的 HTML。我试图理解为什么不允许这样做?

W3C 建议一个交互元素类似于buttona不得包含另一个交互元素。

我可以找到很多提到此规则和一些解决方法的资源,还有一些与这如何影响可访问性和屏幕阅读器相关的资源,但几乎所有这些资源都谈到了这是一项要求但没有解释原因的事实。

https://adrianroselli.com/2016/12/be-wary-of-nesting-roles.html

https://codepen.io/vloux/pen/wXGyOv

在 <button> 中嵌套 <a> 在 Firefox 中不起作用

https://github.com/dequelabs/axe-core/issues/601

我真的无法找到为什么不允许这样做的解释?它会导致任何可用性问题吗?

这是一个相关的问题: 为什么不应该在锚点中使用交互元素?

接受的答案是令人满意的,但不足以使此规则成为要求。使用适当的事件处理可以避免所描述的情况。

此外,如果嵌套的交互式内容无效,我们应该如何处理这样的事情:

一张整体可点击的卡片,里面还有一个可点击的辅助 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 来实现这一点,但这不是语义(?)和功能方面的,它是另一个内部的交互式元素。我试图理解,即使我使用这种解决方法,嵌套交互式元素是否从根本上是错误的?这是一个糟糕的设计/可用性实践吗?

标签: htmlaccessibilitywai-ariasemantic-markup

解决方案


原则上,答案其实很简单。当您单击另一个交互元素内的交互元素时,您应该触发哪个功能?

在您的示例中,如果我单击辅助 CTA,它应该触发辅助 CTA 的功能还是触发卡的功能?

下面的小提琴应该演示问题,进入第一个按钮并按下enter,然后进入 CTA 并按下Enter

显然你可以解决这个问题,但我认为它证明了这一点。

$('.card').on('click', function(){
    console.log("card");
});
$('.cta').on('click', function(){
    console.log("cta");
});
.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;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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" tabindex="0">
   Secondary CTA
  </div>
</button>

然后,这一原则一直延续到屏幕阅读器和其他增强和替代通信 (AAC)设备。

他们在描述子元素时是否应该考虑到父元素?Space如果您在 a 中嵌套一个复选框,它们是否应该允许使用激活,那么<button>应该Enter只影响按钮还是两者都影响?


推荐阅读