我正在使用Bootstrap 3,我有一个自动提取输入。问题是我希望<ul>
使用键盘键滚动,但它不起作用。我认为使用箭头键滚动是一种默认行为,但<ul>
没有这样做。以下是发生的事情:
如果我按两次向下键:
我正在使用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>
答案 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);
}
}
}
});