使用箭头键浏览列表?(JavaScript/JQ)

Navigate through list using arrow keys? (JavaScript/JQ)(使用箭头键浏览列表?(JavaScript/JQ))
本文介绍了使用箭头键浏览列表?(JavaScript/JQ)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法找到如何完成此任务的答案,但这是我多次看到的功能.本质上,我是在呼应一个列表,我想创建使用箭头键/输入突出显示和选择这些项目的能力.有人可以帮助我了解如何实现这一目标吗?我知道如何使用键码(当然),只是不知道如何将其变成功能代码以选择列表中的项目...

I can't seem to find an answer to how to accomplish this, yet it's a feature I've seen several times. Essentially I'm echoing out a list and I would like to create the ability to highlight and select these items using arrow keys/enter. Can someone help give me an idea as to how I can accomplish this? I know how to use keycodes (of course), just not how to turn that into functioning code for selecting items on a list...

我在想也许我必须有某种隐藏的单选按钮来将其标记为选中或未选中...但即便如此我也不知道如何从一个单选按钮跳到另一个单选按钮在列表中.因此,如果有人可以帮我解决这个问题,我将不胜感激.谢谢.

I was thinking maybe I'd have to have some sort of hidden radio button to mark it as selected or not... but even then I don't know how I would jump from one radio button to the other up and down the list. So if anyone could give me a hand with this I'd really appreciate it. Thank you.

推荐答案

由于您没有真正解释您遇到的问题,我只是创建了一个通用解决方案.希望这会有所帮助:

Since you didn't really explain what you're having trouble with, I just created a general solution. Hopefully this helps:

var li = $('li');
var liSelected;
$(window).keydown(function(e) {
    if(e.which === 40) {
        if(liSelected) {
            liSelected.removeClass('selected');
            next = liSelected.next();
            if(next.length > 0) {
                liSelected = next.addClass('selected');
            } else {
                liSelected = li.eq(0).addClass('selected');
            }
        } else {
            liSelected = li.eq(0).addClass('selected');
        }
    } else if(e.which === 38) {
        if(liSelected) {
            liSelected.removeClass('selected');
            next = liSelected.prev();
            if(next.length > 0) {
                liSelected = next.addClass('selected');
            } else {
                liSelected = li.last().addClass('selected');
            }
        } else {
            liSelected = li.last().addClass('selected');
        }
    }
});

JSFiddle:http://jsfiddle.net/Vtn5Y/

这篇关于使用箭头键浏览列表?(JavaScript/JQ)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)