我有一个 <ul>
动态填充的无序列表 <li>
使用 JQuery .ajax 函数列出包含从数据库中获取的数据的元素:
<ul id="here">
<li>Product1</li>
<li>Product2</li>
<li>Product3</li>
<li>Product4</li>
<li>Product5</li>
<li>Product6</li>
</ul>
我可以使用以下 CSS 代码将鼠标悬停在它们上面:
#here{
position: fixed;
background-color: white;
width:175px;
height:300px;
border: 1px solid grey;
display:none;
padding:0px 0px 10px 10px;
}
#here li:hover {
background: #ccc;
cursor: pointer;
}
为填充 <li>
编写的 Javascript 和 JQuery元素是:
var pr= ["Product1", "Product2", "Product3", "Product4", "Product5", "Product6"];
for (var option in pr) {
var newLi = document.createElement("li");
newLi.innerHTML=pr[option];
$("#here").append(newLi);
}
但我需要能够在这些 <li>
之间上下移动使用键盘向上和向下键的元素。谁能指导我该怎么做?
最佳答案
为此使用 CSS 辅助类 --focus
:
var pr = ["Product1", "Product2", "Product3", "Product4", "Product5", "Product6"];
for (var option in pr) {
var newLi = document.createElement("li");
newLi.innerHTML = pr[option];
$("#here").append(newLi);
}
var currentFocus;
$(document).on("keyup", function(e) {
if (e.keyCode === 38 || e.keyCode === 40) {
e.preventDefault();
var children = $("#here").children();
if (currentFocus === undefined) {
currentFocus = 0;
} else {
currentFocus += e.keyCode === 38 ? -1 : 1;
currentFocus < 0 && (currentFocus = children.length - 1);
currentFocus >= children.length && (currentFocus = 0);
}
children.removeClass("--focus");
children.eq(currentFocus).addClass("--focus");
}
});
#here {
background-color: white;
width: 175px;
height: 300px;
border: 1px solid grey;
padding: 0px 0px 10px 10px;
}
#here li:hover,
#here li.--focus {
background: #ccc;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="here">
</ul>
关于javascript - 如何使用向上或向下键在动态填充的 li 元素之间导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39631581/