下面的实现是针对一组三个单选按钮,这些按钮在其 CSS 中具有 display :none
并与标签配对。
现在我一直在尝试向页面添加一些辅助功能选项,以便您可以使用箭头键在单选按钮之间导航,更改每次按键时标签的焦点。但我无法改变焦点,因为我无法改变焦点,焦点仍然停留在标签上的初始标签上。
我已经尝试了一些我在这里看到的关于超时和启用 tabIndex
的选项(希望它作为一个组运行),但没有一个有效。
JS:
$(".radio-type label").keydown(function (e) {
// On Right Key press
if (e.which == 39) {
//Get the list of all buttons and labels
var parentList = $(".radio-type").children();
//Get index of currently focussed button
var indexThis = $(this).index();
//If not at the end of the list
if (indexThis < parentList.length) {
//Get the next in the list and its label
var next = parentList.get(indexThis + 1);
var nextLabel = parentList.get(indexThis + 2);
$(next).change(); //Custom method that changes the selection
//Remove the tab index from old and assign to nextLabel
$(this).removeAttr("tabIndex");
$(nextLabel).attr("tabIndex", "0");
//Change the focus to the new selected label
$(nextLabel).focus();
}
}
e.preventDefault();
});
编辑:HTML 标记(修改名称)
<div class="small-12 medium-12 large-4 columns radio-type @(!Model.ExtendedFilteringEnabled ? "medium-push-4" : "")">
<input type="radio" name="tt" id="ttAll" value="@Model.CurrentBlock.TTAll" checked="checked" />
<label for="ttAll" tabindex="0">All</label>
<input type="radio" name="tt" id="tt1" value="@Model.CurrentBlock.TT1" />
<label for="tt1">1</label>
<input type="radio" name="tt" id="tt2" value="@Model.CurrentBlock.TT2" />
<label for="tt2">2</label>
</div>
更新了 Cory 的 jfiddle:http://jsfiddle.net/n99o3upp/10/ (抱歉一直在打扰它...)
最佳答案
我已经用一些东西更新了你的 fiddle :
更改标记以更轻松地遍历 DOM。标签现在包含他们的输入。
更改事件以触发输入而不是标签
将您的设置方法更改为使用
prop
而不是attr
,因为这将在 DOM 中设置实际值对
if
语句进行比较以查找小于length -1
的索引,因为索引基于 0,长度基于 1。使 CSS 通过定位而不是显示来隐藏输入。我在 fiddle 中对此进行了注释,以便您可以看到输入更改
添加了 e.preventDefault() 以停止干扰您的 js 的默认浏览器操作
新的 fiddle 在这里:http://jsfiddle.net/n99o3upp/16/
但是,我不确定这段代码是否必要,因为没有它,浏览器无论如何都会做同样的事情。当 DOM 被这样标记时,左右键会自动将焦点移动到组中的下一个输入。
我认为您可以删除 keydown
事件函数并只保留 change
事件函数,这将执行您想要的相同操作。您可以通过向右移动输入,然后向左移动来测试它。两者都有效,但向右移动由您的脚本控制,向左移动是自动的。
关于javascript - jQuery .focus() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25479699/