【问题标题】:ul list not scrolling on key press but it does with mouse wheelul 列表在按键时不滚动,但它使用鼠标滚轮滚动
【发布时间】:2014-05-12 06:11:24
【问题描述】:

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

如果我按两次向下键:

我使用的是 Bassjobsen 开发的typeahead

HTML 代码:

<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 中的所有项目。这就是为什么我需要滚动它们。

我将这个内联样式添加到生成的&lt;ul&gt;

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>

【问题讨论】:

  • 关于该问题的任何更新?
  • 你修好了吗?

标签: javascript html css twitter-bootstrap-3 bootstrap-typeahead


【解决方案1】:

最终编辑:

好吧,我开始在解决这个问题上玩得很开心,最后(希望你仍然需要解决方案!)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);
            }
        }
    }
});

【讨论】:

  • 感谢您的宝贵时间!但这不是我想要的。在您的解决方案中,列表的所有元素都会显示出来,这就是您可以选择它们的原因。在我的真实应用中,ul 有大约 70 个项目,所以你需要 ul 滚动,每次 ul 滚动时,我都需要显示所选元素。
猜你喜欢
  • 1970-01-01
  • 2013-04-20
  • 1970-01-01
  • 2011-09-29
  • 2018-04-20
  • 2012-06-07
  • 2010-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多