这个答案肯定属于“指向正确方向”的类别,因为我不知道您是否已经有代码以及它是什么样的(如果存在的话)。
你说你已经创建了一个带有建议的下拉菜单,所以我将省略 CSS 和 JS 来设置样式和定位。
假设下拉列表包含以下标记:
<div id="suggestiondropdown">
<span class="suggestion" data-page="[URL of page]">Suggestion 1</span>
<span class="suggestion" data-page="[URL of page]">Suggestion 2</span>
<span class="suggestion" data-page="[URL of page]">Suggestion 3</span>
<span class="suggestion" data-page="[URL of page]">Suggestion 4</span>
<span class="suggestion" data-page="[URL of page]">Suggestion 5</span>
</div>
使用此 JS,您应该能够使用箭头键在建议之间移动:
var suggestions = document.querySelectorAll(".suggestion"); // Now suggestions is an array with the spans
var index = 0;
document.onkeypress = function(e) {
// Style the selected as normal here:
suggestions[index].style.backgroundColor = "#FFFFFF";
if (e.keyCode == 38) { // UP!
if (index <= 0) index = suggestions.length;
index--;
}
else if (e.keyCode == 40) { // DOWN!
if (index >= suggestions.length -1) index = -1;
index++;
}
else if (e.keyCode == 13) { // ENTER!
var page = suggestions[index].dataset.page;
window.location.href = page; // Or with relative URLs, first prepend the base URL.
}
// Style the selected one as selected here.
// I don't know how you want it, so I'll just give the selected one a blue background.
suggestions[index].style.backgroundColor = "#0000FF"; // Never mind the ugly shade
}
未经测试