我想在获得tabindex的元素上创建导航,然后按下键我想获得该元素的索引,将其传递给计数器并将下一个元素设置为活动状态。问题是我无法获得聚焦的元素索引。代码:
var focusable = Array.from(document.querySelectorAll('[tabindex]'));
focusable[1].focus()
window.addEventListener('keydown', function(e) {
var counter;
if (e.keyCode == '38') {
//here i want to pass the index of elment
//from array which is focused and pass it to counter
console.log('up');
counter++
console.log(counter)
focusable[counter].focus()
}
});
答案 0 :(得分:0)
您的querySelectorAll("[tabindex]")
不会返回任何元素,除非他们明确设置了tabindex
属性( ,但如果你填充数组,那么如何做这样的事情:
// Make sure all the intended elements are placed into the array:
var focusable = Array.from(document.querySelectorAll('input, select, textarea, button'));
console.log(focusable); // Test
// First item is item 0, not 1
focusable[0].focus()
// This needs to be outside the event handler or it will get reset every time a key is pressed
var counter = 0;
window.addEventListener('keydown', function(e) {
if (e.keyCode == '38') {
// Can't let counter get higher than max index
counter = (counter === focusable.length -1) ? 0 : ++counter;
focusable[counter].focus(); // set focus to next item in the array
}
});
<input type="text">
<select>
<option>test</option>
</select>
<textarea></textarea>
<button>test</button>