应用鼠标悬停样式时,按箭头键导航删除应用于列表项的选定类

时间:2016-09-10 21:56:24

标签: javascript jquery html css

在文本框中按下向上/向下箭头键时,所选类将应用于列表项。如果我将鼠标指针移动到列表项上并同时按向上/向下箭头键,则将悬停和所选类都应用于列表项。如何切换悬停和选定的类类似于选择输入选项?

http://jsfiddle.net/AyAZx/790/

$('#college').keyup(function(e) {

  var $listItems = $('.field-wrap li');
  var key = e.keyCode,
    $selected = $listItems.filter('.selected'),
    $current;

  $listItems.removeClass('selected');


  var menu = $('#college_list');
  var height = $selected.outerHeight();
  var top = menu.scrollTop();
  var menuHeight = menu[0].scrollHeight;

  if (key == 40) // Down key
  {
    if (!$selected.length || $selected.is(':last-child')) {
      $current = $listItems.eq(0);
      menu.scrollTop(0);
    } else {
      $current = $selected.next();
      menu.scrollTop(top + height);
    }

    $current.addClass('selected');
  }

  if (key == 38) // Up key
  {
    if (!$selected.length || $selected.is(':first-child')) {
      $current = $listItems.last();
      menu.scrollTop(menuHeight + height);
    } else {
      $current = $selected.prev();
      menu.scrollTop(top - height);
    }
    $current.addClass('selected');
  }

});
.field-wrap ul {
  width: 93%;
  margin-top: 1px;
  border: 1px solid #3498DB;
  position: absolute;
  z-index: 9;
  background: white;
  list-style: none;
  max-height: 100px;
  overflow-y: auto;
}
.field-wrap ul li {
  padding: 2px;
  border: solid grey;
  border-width: 0 0 2px 0;
}
.field-wrap ul li:hover {
  background: #2980B9;
}
<div class="field-wrap">
  <input type="text" id="college" placeholder="Name" required autocomplete="off" />
  <ul id="college_list">
    <li>abc</li>
    <li>def</li>
    <li>asdff</li>
    <li>dasdf</li>
    <li>asdef</li>
    <li>asdf</li>
    <li>asf</li>
    <li>asdef</li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:1)

我担心在这种情况下你必须用mousemove事件替换css:hover:

$('#college_list li').mousemove(function() {
   $('.field-wrap li').removeClass('selected');
   $(this).addClass('selected');
});