可访问的自定义样式复选框

Accessible custom styled checkbox

我正在使用标签元素创建自定义样式的复选框。 本质上,我将它用作按钮,以便稍后使用 :checked 选择器执行一些样式设置。我没有将值提交到表单。

<input type="checkbox" id="agree" style="display:none" />
.......
<!-- few more divs here -->
.......
<label for="agree" role="button">Click here</label>
<div>This div will be styled if the checkbox is ticked</div>

我的问题是,从可访问性的角度来看,这是否正确? 有没有更语义化的方式来做到这一点? (css只须提及)

我需要一个自定义样式的复选框。

我认为正确的语义方式是使用 <button>,但它不能用作标签并且不会勾选复选框..

仅使用 CSS 和 HTML 我可能会建议以下解决方案:

<label for='checkbox'>
     <span style='cursor:pointer;border:1px solid red; background:yellow;padding:5px;border-radius:5px;'>Click</span>
</label>
<input id='checkbox' type='checkbox' />

所以你不需要按钮。您可以自定义跨度。

勾选fiddlehttps://jsfiddle.net/an0tcLmc/

标准的方法是利用 aria-checkedrole=checkbox 属性获利,但这需要 Javascript:

<label for="agree">Click here</label>
<div id="agree" role="checkbox" aria-checked="true" tabindex="0">
       This div will be styled if the checkbox is ticked</div>

您的示例中的可访问性失败有多个:

请注意,您可以完美地使用标准 checkbox 元素并在其上应用一些 css 而无需完全隐藏它。

<label>
    <input type="checkbox" id="agree" value="1" />
    <div>I agree with the above elements</div>
</label>

-----
/* the input would be hidden but still focusable */
#agree {width: 0px; margin-left: 2px; overflow: hidden;}

/* when focusing the element, we will outline the text to make the focus visible */
#agree:focus + div {outline: dotted 2px blue}

/* default when unticked */
#agree + div {background-image: url("ko.png") no-repeat; border: solid transparent 2px;}

/* default when ticked */
#agree:checked + div {background-image: url("ok.png") no-repeat; border: solid green 2px;}

这需要您的 CSS 产生明显的差异,而不是仅仅依靠颜色的使用。

根据@Adam 的回答,他链接到一个资源 2.2 Second rule of ARIA use 这给了我一个很好的提示如何解决我的问题。

而不是这样做

<label for="agree" role="button">Click here</label>

正确的方法是

<label for="agree"><span role="button">Click here</span></label>

因为我不能使用 <button>(这将与勾选复选框的标签冲突),我使用的是 role="button".

的跨度