ul列表不滚动按键,但它与鼠标滚轮 [英] ul list not scrolling on key press but it does with mouse wheel
问题描述
我正在使用Bootstrap 3,我有一个自动绑定输入。问题是,我想用< ul>
滚动键盘键,但它不工作。我认为用箭头键滚动是一种默认行为,但< ul>
不会这样做。这是发生了什么:
I'm working with Bootstrap 3 and i have an autossugest input. The problem is that i want the <ul>
to scroll with the keyboard keys but it doesn't work. I think scrolling with arrows keys is a default behavior but the <ul>
doesn´t do it. Here is what is happening:
如果我按下向下键两次:
If i press the down key twice:
I'm using the typeahead developed by Bassjobsen.
HTML代码:
<input type="text" class="form-control" data-provide="typeahead" id="test">
Javascript(使用JQuery.js)代码:
Javascript (with JQuery.js) code:
$('document').ready (function () {
$('#test').typeahead({
source: ['algo', 'pepe', 'algo2', 'algo34', 'pepe3', 'algo42'],
items: 'all',
minLength: 2
});
});
我将项目
设置为 all
显示 source
中的所有项目。
I set items
to all
to show all items in source
. That's why i need to scroll them.
我将这个内联样式添加到生成的< ul>
:
I added this inline style to the generated <ul>
:
style="max-height: 50px; overflow-y: auto;"
所以这是由Bassjobsens库生成的代码:
So this is the code generated by Bassjobsens library:
<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>
推荐答案
Final Edit:
Final
好吧,我开始有太多的乐趣想出来,最后有(希望你仍然需要解决方案!) 这里 是一个有效的解决方案,建立起我之前发布的内容,希望它是你在寻找!
Alright, I started having too much fun figuring this out, and finally have (hopefully you still need the solution!) Here is a working solution, building off of what I posted earlier. I hope it's what you were looking for!
$('#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列表不滚动按键,但它与鼠标滚轮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!