Dav*_*ave 10 html css jquery css3 html-lists
我正在使用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");
}
});
Run Code Online (Sandbox Code Playgroud)
问题是,如果你不断点击向下键(例如),最终你将无法看到所选项目.如何调整内容以使所选项始终可见?说明问题的小提琴在这里 - http://jsfiddle.net/sge8g5qu/1/.
Gab*_*oli 11
最后,您还可以将类添加到nextElement调用中.scrollIntoView( false ).
if(nextElement !== null) {
$(nextElement).addClass("selected");
nextElement.scrollIntoView(false); // added this line
}
Run Code Online (Sandbox Code Playgroud)
更新小提琴:http://jsfiddle.net/gaby/6fjnnu55/