javascript - 如何使用向上或向下键在动态填充的 li 元素之间导航

标签 javascript jquery html css navigation

我有一个 <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/

相关文章:

javascript - 用于 url 验证的正则表达式(未终止的括号错误)

javascript - 检测是什么脚本对 DOM 进行了更改

html - 在 CSS 中以最小高度垂直居中标题和段落

javascript - 将图像添加到事件 - 完整日历

javascript - JQuery 异步成功

javascript - 如何将对象作为参数传递并在构造函数内引用它

javascript - 在javascript中改变运动方向时旋转css sprite

javascript - ASP Classic 和 JavaScript 检查 session 状态

JQuery 可在固定高度的 div 中拖动和滚动

Gruntfile.js 中的 Javascript 变量?