我希望能够仅使用 JavaScript 使用箭头键浏览网页上的一些可聚焦元素。
我找到了一个很好的解决方案here 。唯一的问题是,它使用了 jQuery,而我不想使用它。该答案的作者告诉我,仅使用 JavaScript 就可以达到相同的效果。我只是不知道如何,甚至不知道要寻找什么。我还是个初学者,所以如果这是一个显而易见的问题,我很抱歉。
这是我想要实现的 jQuery 版本:
<input class='move' /><input class='move' /><input class='move' />
$(document).keydown(
function(e)
{
if (e.keyCode == 39) {
$(".move:focus").next().focus();
}
if (e.keyCode == 37) {
$(".move:focus").prev().focus();
}
}
);
最佳答案
您可以使用以下功能:
querySelectorAll()
或getElementsByClassName
用于选择元素。addEventListener()
用于绑定(bind)事件监听器。previousElementSibling
和nextElementSibling
用于获取previous()
和next()
元素。
var inputs = document.getElementsByClassName("move");
for (var i = 0; i < inputs.length; i++)
inputs[i].addEventListener("keyup", function (event) {
if (event.keyCode == 37) {
if (this.previousElementSibling) {
this.previousElementSibling.focus();
}
}
else if (event.keyCode == 39) {
if (this.nextElementSibling) {
this.nextElementSibling.focus();
}
}
}, false);
<input class='move' />
<input class='move' />
<input class='move' />
有关更多替换内容,请查看:You Might Not Need jQuery 。 😇
关于javascript - 将焦点转移到 keydown - 仅 JavaScript - 无 jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53942870/