在我的项目中,我正在向li
元素动态添加ul
标记,然后当焦点位于textarea
元素上时,我正在尝试在第一个li
元素上生成悬停效果每当用户按下down arrow key
时,{1}}元素。不知怎的,我的努力没有奏效。
我到现在为止尝试的代码如下:
HTML
<textarea id="result" rows="4" cols="50"></textarea>
<ul class="autoComplete"></ul>
CSS
.autoComplete li {
background-color:#E1E1E1;
cursor: hand;
cursor: pointer;
}
.autoComplete li:hover {
background-color:#BDBDBD;
}
JS
var result = $('#result');
var autoComplete = $('.autoComplete');
result.keydown(function (event) {
if (event.keyCode == 40) {
if (autoComplete.children('li').length > 0) {
console.log('down');
//should work with IE
autoComplete.children(":first").focus().hover();
}
}
});
PS:解决方案应该是crossbrowser(IE8 +)
答案 0 :(得分:2)
尝试
CSS
.autoComplete li {
background-color:#E1E1E1;
cursor: hand;
cursor: pointer;
}
.autoComplete li.hover {
background-color:#BDBDBD;
}
JS
var result = $('#result');
var autoComplete = $('.autoComplete');
result.keyup(function (event) {
console.log('keydown');
if (event.keyCode == 40) {
if (autoComplete.children('li').length > 0) {
console.log('down');
//should work with IE
autoComplete.children(":first").mouseenter();
}
}
});
autoComplete.on('mouseenter', 'li', function(){
$(this).addClass('hover');
}).on('mouseleave', 'li', function(){
$(this).removeClass('hover');
});
演示:Fiddle