2016-10-05 33 views
2

我使用标签元素来创建自定义样式复选框。 本质上,我使用它作为按钮,稍后使用: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>正确的语义的方式,但后来它不是作为一个公司工作,并不会勾选复选框..

+0

为什么你不想使用Jquery? –

+0

我宁愿避免使用JavaScript,只要有一种方法只用CSS即可。 Css更快,更可靠。 – Alvarez

+1

选中此项:[无线电控制网页设计](http://alistapart.com/article/radio-controlled-web-design#section12),一篇关于CSS Checkbox Hack所需知识的绝佳文章,其中包括a11y 。 – 5aledmaged

回答

0

基于@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"的跨度。

-1

只使用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' /> 

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

检查小提琴https://jsfiddle.net/an0tcLmc/

+0

谢谢,但我知道如何样式复选框这样,我的问题是关于可访问性 – Alvarez

+0

这是什么意思?你点击按钮,复选框被选中/取消选中。您可以隐藏复选框并使用按钮。 –

+0

我没有使用表单中的复选框。我正在使用一个复选框,以便稍后从受检选择器中受益。问题就在于语义上这是否正确。我知道

2

做到这一点的标准方式是采取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> 

在你的例子中的可访问性的失败是多方面的:

注上使用role属性,可以完美使用标准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使不依赖于单独使用的颜色明显的区别。

+0

基于你关于不改变本地语义的链接资源,我了解了如何获得我的东西寻找。谢谢! – Alvarez