【发布时间】:2017-01-06 03:56:58
【问题描述】:
我正在使用 jQuery 1.12。我有一个带有 LI 元素的样式化 UL。当 DIV 具有焦点时,我使用以下代码使用键盘上的向上或向下箭头选择这些元素...
$(".select").bind('keydown', function(event) {
var currentElement = $(this).find(".select-options li.selected");
if (currentElement.length == 0) {
currentElement = $(this).find(".select-options li")[0];
$(currentElement).addClass("selected");
return;
} // if
var nextElement;
switch(event.keyCode){
// case up
case 38:
nextElement = $(this).find(".select-options li")[($(this).find(".select-options li").index(currentElement) - 1) % $(this).find(".select-options li").length];
break;
case 40:
nextElement = $(this).find(".select-options li")[($(this).find(".select-options li").index(currentElement) + 1) % $(this).find(".select-options li").length];
break;
}
$(this).find(".select-options li").removeClass("selected");
if(nextElement !== null) {
$(nextElement).addClass("selected");
}
});
问题是,如果您连续单击向下键(例如),最终您将无法看到所选项目。如何调整以使所选项目始终可见?说明问题的小提琴在这里——http://jsfiddle.net/sge8g5qu/1/。
【问题讨论】:
-
最好的办法是将其限制在屏幕高度内。这就是 Facebook 或 Google 所做的。
-
你编辑我的小提琴来说明你在说什么吗?
-
正如How do I mimic keyboard behavior in my styled select dropdown? 中提到的,最简单的解决方案是使用jQuery UI
selectMenu小部件,该小部件可用且经过全面测试。您还可以查看他们的代码以了解他们是如何做到的。
标签: jquery html css html-lists