可点击的li键盘导航链接

时间:2018-08-02 07:59:03

标签: javascript jquery html

我有一个li列表,您可以使用键盘箭头进行导航,它可以正常工作,但是我希望能够使用键盘上的Enter按钮单击链接。我还没有找到解决方案。

Heres the code im using

var li = $('li');
var liSelected;
$(window).keydown(function(e) {
  if (e.which === 40) {
    if (liSelected) {
      liSelected.removeClass('selected');
      next = liSelected.next();
      if (next.length > 0) {
        liSelected = next.addClass('selected');
      } else {
        liSelected = li.eq(0).addClass('selected');
      }
    } else {
      liSelected = li.eq(0).addClass('selected');
    }
  } else if (e.which === 38) {
    if (liSelected) {
      liSelected.removeClass('selected');
      next = liSelected.prev();
      if (next.length > 0) {
        liSelected = next.addClass('selected');
      } else {
        liSelected = li.last().addClass('selected');
      }
    } else {
      liSelected = li.last().addClass('selected');
    }
  }
});
li {
  color: blue;
}

li.selected {
  background: yellow;
  color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li><a href="#">First Link</a></li>
  <li> <a href="#">Second Link</a></li>
  <li> <a href="#">Third Link</a></li>
  <li> <a href="#">Third Link</a></li>
</ul>

2 个答案:

答案 0 :(得分:2)

Enter键的键码为13。因此,您可以使用以下代码来查看另一个else if子句:

else if (e.which === 13) {
  if (liSelected) {
    $(liSelected).find('a')[0].click();
  }
}

答案 1 :(得分:0)

var li = $('li');
var liSelected = li.eq(0).addClass('selected');
$(window).keydown(function(e) {
    if (e.which === 13) {
        if (liSelected) {
            window.open(liSelected.children(':first').attr('href'))
        }
    }
    else if (e.which === 40) {
        if (liSelected) {
            liSelected.removeClass('selected');
            next = liSelected.next();
            if (next.length > 0) {
                liSelected = next.addClass('selected');
            } else {
                liSelected = li.eq(0).addClass('selected');
            }
        } else {
            liSelected = li.eq(0).addClass('selected');
        }
    }
    else if (e.which === 38) {
        if (liSelected) {
            liSelected.removeClass('selected');
            next = liSelected.prev();
            if (next.length > 0) {
                liSelected = next.addClass('selected');
            } else {
                liSelected = li.last().addClass('selected');
            }
        } else {
            liSelected = li.last().addClass('selected');
        }
    }
});
    li {
        color: blue;
    }

    li.selected {
        background: yellow;
        color: black;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul>
        <li><a href="http://www.google.com" target="_blank">Google</a></li>
        <li><a href="#2">Second Link</a></li>
        <li><a href="#3">Third Link</a></li>
        <li><a href="#4">Third Link</a></li>
    </ul>