[英]arrow keys navigation through li (no jquery)
我試圖想出一種方法來創建一個非常基本的自動完成,而沒有第三方依賴。 到目前為止,我已經用ajax調用填充結果列表,並且在每個li上使用鼠標onclick事件,腳本完成所謂的字段。
我需要實現的是一個基於純js的上/下/輸入鍵導航系統,經過幾個小時的搜索我放棄了。 這個小提琴非常完美地解釋了我的情況,區別在於它確實需要jQuery。
我寧願不在這里粘貼任何我自己的代碼,因為最后的目標是學習這個過程,但是因為我要鏈接到jsfiddle,所以我需要這樣的小提琴。
小提琴HTML:
<div id="MainMenu">
<ul>
<li class="active"><a href="#">PATIENT TEST</a></li>
<li><a href="#">QC TEST</a></li>
<li><a href="#">REVIEW RESULTS</a></li>
<li><a href="#">OTHER</a></li>
</ul>
</div>
<a href="#" id="btnUp">Up</a>
<a href="#" id="btnDown">Down</a>
小提琴JS:
$(document).ready(function () {
$('#btnDown').click(function () {
var $current = $('#MainMenu ul li.active');
if ($current.next().length > 0) {
$('#MainMenu ul li').removeClass('active');
$current.next().addClass('active');
}
});
$('#btnUp').click(function () {
var $current = $('#MainMenu ul li.active');
if ($current.prev().length > 0) {
$('#MainMenu ul li').removeClass('active');
$current.prev().addClass('active');
}
});
$(window).keyup(function (e) {
var $current = $('#MainMenu ul li.active');
var $next;
if (e.keyCode == 38) {
$next = $current.prev();
} else if (e.keyCode == 40) {
$next = $current.next();
}
if ($next.length > 0) {
$('#MainMenu ul li').removeClass('active');
$next.addClass('active');
}
});
});
非常感謝任何願意指出我正確方向的人。
事實證明這比我預期的要簡單,而且我已經提出了以下代碼,這些代碼顯然可以很好地完成工作。
要考慮的事項是:
這是基本的HTML:
<input type="text" name="main_input" id="input" />
<ul id="list">
<li class="listElement"><a href="#" tabindex="1">li content</a></li>
<li class="listElement"><a href="#" tabindex="1">li content</a></li>
<li class="listElement"><a href="#" tabindex="1">li content</a></li>
</ul>
這里是JS函數,當上面的列表被填充並顯示時觸發:
function scrollList() {
var list = document.getElementById('list'); // targets the <ul>
var first = list.firstChild; // targets the first <li>
var maininput = document.getElementById('input'); // targets the input, which triggers the functions populating the list
document.onkeydown = function(e) { // listen to keyboard events
switch (e.keyCode) {
case 38: // if the UP key is pressed
if (document.activeElement == (maininput || first)) { break; } // stop the script if the focus is on the input or first element
else { document.activeElement.parentNode.previousSibling.firstChild.focus(); } // select the element before the current, and focus it
break;
case 40: // if the DOWN key is pressed
if (document.activeElement == maininput) { first.firstChild.focus(); } // if the currently focused element is the main input --> focus the first <li>
else { document.activeElement.parentNode.nextSibling.firstChild.focus(); } // target the currently focused element -> <a>, go up a node -> <li>, select the next node, go down a node and focus it
break;
}
}
}
對於有點混亂的代碼布局提前道歉,我想出的功能有點復雜,我為了解釋目的而剝離了大部分內容。
毋庸置疑,我期待有關上述解決方案的任何評論,包括錯誤,改進或已知的兼容性問題。
你寫了
的tabindex = “1”
為什么不只是tabindex =“0”? 只有在想要改變默認導航順序時才需要使用大於0的正數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.