首页 > 解决方案 > 如何在隐藏的单选按钮上使用键盘选项卡

问题描述

在一个表单中,我有以下通用 html:

<input type="text" autofocus placeholder="Full name" />

<input name="yesno" type="radio" value="Yes" id="yes">
<label for="yes">Yes</label>

<input name="yesno" type="radio" value="No" id="no">
<label for="no">No</label>

在这种形式中,我可以TAB从文本中input插入单选按钮并使用左/右键选择“是”或“否”。

然后我应用一些样式来使单选按钮符合设计:

input[type="text"] {
  height: 60px;
  text-indent: 1em;
}

input[type="radio"] {
  display: none;
}

input[type="radio"]+label {
  color: #106AA2;
  background: #fff;
  font-weight: 100;
  text-align: center;
  padding: 1em 2em;
  height: auto;
  font-size: 1.3em;
  border: 1px solid #C5DBE8;
  display: inline-block;
  letter-spacing: inherit;
  vertical-align: middle;
  cursor: pointer;
}

input[type="radio"]:checked+label {
  background: linear-gradient(#1275B2, #106AA2);
  color: #fff;
}
<input type="text" autofocus placeholder="Full name" />

<input name="yesno" type="radio" value="Yes" id="yes">
<label for="yes">Yes</label>

<input name="yesno" type="radio" value="No" id="no">
<label for="no">No</label>

但是,我现在不能再TAB从文本input到单选按钮了。我知道这是因为我有display:none他们。

是否有一种跨浏览器的方式可以让用户使用TAB这些单选按钮?

理想情况下,我正在寻找纯 CSS 的解决方案,但是我对 javascript 解决方案持开放态度。

标签: javascripthtmlcssuser-experience

解决方案


不要让它不存在,display: none;只是缩小它。

您可以设置widthandheight0使输入不可见,但可以使用选项卡。

input[type="text"] {
  height: 60px;
  text-indent: 1em;
}

input[type="radio"] {
  /* display: none; */
  width: 0;
  height: 0;
}

input[type="radio"]+label {
  color: #106AA2;
  background: #fff;
  font-weight: 100;
  text-align: center;
  padding: 1em 2em;
  height: auto;
  font-size: 1.3em;
  border: 1px solid #C5DBE8;
  display: inline-block;
  letter-spacing: inherit;
  vertical-align: middle;
  cursor: pointer;
}

input[type="radio"]:checked+label {
  background: linear-gradient(#1275B2, #106AA2);
  color: #fff;
}
<input type="text" autofocus placeholder="Full name" />

<input name="yesno" type="radio" value="Yes" id="yes">
<label for="yes">Yes</label>

<input name="yesno" type="radio" value="No" id="no">
<label for="no">No</label>


推荐阅读