如何使用向上或向下键在动态填充的li元素之间导航 [英] how to navigate between dynamically populated li elements using up or down keys

查看:104
本文介绍了如何使用向上或向下键在动态填充的li元素之间导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个<ul>无序列表,其中动态填充了<li>列表元素,并使用JQuery .ajax函数从数据库获取了数据:

I have an <ul> unordered list with dynamically populated <li> list elements with data taken from database using JQuery .ajax function:

<ul id="here">
<li>Product1</li>
<li>Product2</li>
<li>Product3</li>
<li>Product4</li>
<li>Product5</li>
<li>Product6</li>
</ul>

我可以使用以下CSS代码将鼠标悬停在这些代码上:

I can hover over these using following css code:

#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是:

The Javascript and JQuery written for populating the <li> elements is:

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>元素之间上下移动.谁能指导我该怎么做?

but I need to be able to move up and down among these <li> elements using keyboard up and down keys. Can anyone guide me how can I do this?

推荐答案

为此使用CSS帮助器类--focus:

Using a CSS helper class --focus for this:

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>

这篇关于如何使用向上或向下键在动态填充的li元素之间导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆