如果按下向上箭头键或向下箭头键,如何上下移动和聚焦项目?我需要使用纯JavaScript来做到这一点。
<div id="list">
<div class="item" onclick="ItemOnClick('10000001')" onkeypress="ItemOnClick('10000001')">How are you?</div>
<div class="item" onclick="ItemOnClick('10000002')" onkeypress="ItemOnClick('10000002')">What's your name?</div>
<div class="item" onclick="ItemOnClick('10000003')" onkeypress="ItemOnClick('10000003')">Are you fine?</div>
</div>
<input autocomplete=off id=input onkeyup="InputOnKeyUp(this);" type=search>
<script>
function InputOnKeyUp(Input) {
if (event.keyCode == 38) {
// move up to focus an item from list
} else if (event.keyCode == 40) {
// move down to focus an item from list
}
}
</script>
答案 0 :(得分:0)
首先,您需要给元素tabindex
赋予div
重点。另外,input#input
上的键控很愚蠢,因为您总是通过聚焦列表元素而失去焦点-因此只需将键控放在#list
本身上即可。
为防止滚动,您可以将onkeyup
更改为onkeydown
。
function ItemOnClick(number){console.log(number)}
function InputOnKeyUp(input){
event.stopPropagation();
event.preventDefault ? event.preventDefault() : event.returnValue = false;
var tList = document.querySelector('#list'),
tNodes = tList.children,
tIndex = ~~tList.getAttribute('data-tabindex');
if(event.keyCode == 38){
tIndex -= 1
// move up to focus an item from list
}
else if (event.keyCode == 40){
tIndex += 1
// move down to focus an item from list
};
if(tIndex >= tNodes.length){
tIndex = 0 //REM: We select the first item
};
if(tIndex < 0){
tIndex = tNodes.length -1 //REM: We select the last item
};
if(tNodes[tIndex]){
tNodes[tIndex].focus(); //REM: Focusing the element
tList.setAttribute('data-tabindex', tIndex) //REM: Storing the selected item
}
};
//REM: Focus the first item
document.querySelector('#list').children[0].focus();
<!-- Give the items a tabindex to allow them to get focused. Also enables tab and shift+tab.
Also we move the keyup to the #list. Else the input keeps losing focus. -->
<div id="list" onkeydown="InputOnKeyUp(this);">
<div class="item" onclick="ItemOnClick('10000001')" onkeypress="ItemOnClick('10000001')" tabindex = '1'>How are you?</div>
<div class="item" onclick="ItemOnClick('10000002')" onkeypress="ItemOnClick('10000002')" tabindex = '2'>What's your name?</div>
<div class="item" onclick="ItemOnClick('10000003')" onkeypress="ItemOnClick('10000003')" tabindex = '3'>Are you fine?</div>
</div>
<!--
<input autocomplete=off id=input " type=search onkeyup="InputOnKeyUp(this);>
-->