1
我做了一個搜索表單,可以使用箭頭向上和向下鍵在結果之間導航。但只適用於第一個結果,如果要再次導航,則需要再次關注搜索輸入文本,如果我不這樣做,則無法再次導航。只專注於第一個元素
的jsfiddle:http://jsfiddle.net/gaw7g332/6/
JS代碼:
/* JS File */
// Start Ready
$(document).ready(function() {
// Icon Click Focus
$('.buscar-icon').click(function(){
$('input#search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#search").on("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('p#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('p#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
$("input#search").on("keydown", function(e) {
var $listItems = $('ul#results li');
var $listItemsa = $('ul#results li a');
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;
if (key != 40 && key != 38) return;
$listItems.removeClass('selected');
if (key == 40) // Down key
{
if (! $selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
event.preventDefault();
}
else {
$current = $selected.next();
event.preventDefault();
}
}
else if (key == 38) // Up key
{
if (! $selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
event.preventDefault();
}
else {
$current = $selected.prev();
event.preventDefault();
}
}
$.fn.focusWithoutScrolling = function(){
var x = $(document).scrollLeft(), y = $(document).scrollTop();
this.focus();
window.scrollTo(x, y);
return this; //chainability
};
var $currenta = $current.children();
$currenta.focusWithoutScrolling();
$current.addClass('selected');
event.preventDefault();
});