javascript - Shift focus onkeydown - JavaScript Only - No jQuery
问题描述
I would like to be able to navigate through some of the focusable elements on my webpage with the arrow keys, using JavaScript only.
I found a great solution here. Only thing is, it uses jQuery, which I don't want to use. I was told by the author of that answer that it is possible to achieve the same effect with JavaScript only. I just don't know how, or even what to look for. I'm still a beginner, so I am sorry if it is an obvious question.
This is the jQuery version of what I want to achieve:
<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();
}
}
);
解决方案
You can use the following functions:
querySelectorAll()
orgetElementsByClassName
for selecting elements.addEventListener()
for binding the event listener.previousElementSibling
andnextElementSibling
for getting theprevious()
andnext()
elements.
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' />
For more replacement stuff, check out: You Might Not Need jQuery.
推荐阅读
- visual-studio-code - VS Code:将文件作为最后一个选项卡而不是当前选项卡打开
- java - 它的正确答案是 22。但我得到 24。我错在哪里?我最后评估赋值运算符 += 因为它的优先级最低
- python - 通过 cffi 在 python 中使用 int * (array) 返回值?
- json - 谷歌表格是否停止允许 json 访问?
- java - Intellij、Gradle、SpringBootApplication、未运行、“内容根文件夹”有问题?
- python - 按特定顺序将矩阵转换为向量
- java - CRUDRepository 的 Spring Data Redis 问题
- javascript - 有没有办法找出公会剩下多少个表情符号槽可以使用?
- xpath - 如何在基于 XML 的 Jasper 报告中指定特定行
- azure - 具有共享高级磁盘的 Azure 虚拟机 - 看不到数据