2017-07-19 77 views
0

我想要創建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

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>