ul列表不能在按键上滚动,但它与鼠标滚轮一起滚动

时间:2014-04-01 12:49:38

标签: javascript html5 css3 twitter-bootstrap-3 bootstrap-typeahead

我正在使用Bootstrap 3,我有一个自动提取输入。问题是我希望<ul>使用键盘键滚动,但它不起作用。我认为使用箭头键滚动是一种默认行为,但<ul>没有这样做。以下是发生的事情:

enter image description here

如果我按两次向下键:

enter image description here

我正在使用Bassjobsen开发的typeahead

HTML code:

<input type="text" class="form-control" data-provide="typeahead" id="test">

Javascript(使用JQuery.js)代码:

$('document').ready (function () {

  $('#test').typeahead({
      source: ['algo', 'pepe', 'algo2', 'algo34', 'pepe3', 'algo42'],
      items: 'all',
      minLength: 2
  });

});

我将items设置为all以显示source中的所有项目。这就是我需要滚动它们的原因。

我将此内联样式添加到生成的<ul>

style="max-height: 50px; overflow-y: auto;"

所以这是Bassjobsens库生成的代码:

<ul class=" dropdown-menu" style="max-height: 50px; overflow-y: auto; top: 73px; left: 20px; display: none;" "="">
  <li class="active">
     <a href="#"><strong>al</strong>go</a>
  </li>
  <li>
     <a href="#"><strong>al</strong>go2</a>
  </li>
  <li>
     <a href="#"><strong>al</strong>go34</a>
  </li>
  <li>
     <a href="#"><strong>al</strong>go42</a>
  </li>
</ul>

1 个答案:

答案 0 :(得分:2)

最终编辑:

好吧,我开始有太多的乐趣来解决这个问题,最后(希望你仍然需要解决方案!)Here是一个有效的解决方案,建立在我之前发布的内容之上。我希望你能找到它!

$('#test').keydown(function(e) {
    if($('.dropdown-menu').is(':visible')) {

        var menu = $('.dropdown-menu');
        var active = menu.find('.active');
        var height = active.outerHeight(); //Height of <li>
        var top = menu.scrollTop(); //Current top of scroll window
        var menuHeight = menu[0].scrollHeight; //Full height of <ul>

        //Up
        if(e.keyCode == 38) {
            if(top != 0) {
                //All but top item goes up
                menu.scrollTop(top - height);
            } else {
                //Top item - go to bottom of menu
                menu.scrollTop(menuHeight + height);
            }
        }    
        //Down
        if(e.keyCode == 40) {
            //window.alert(menuHeight - height);
            var nextHeight = top + height; //Next scrollTop height
            var maxHeight = menuHeight - height; //Max scrollTop height

            if(nextHeight <= maxHeight) {
                //All but bottom item goes down
                menu.scrollTop(top + height);
            } else {
                //Bottom item - go to top of menu
                menu.scrollTop(0);
            }
        }
    }
});