1

在我的项目中,我正在向元素li动态添加标签ul,然后当焦点位于textarea元素上时,我试图li在用户按下时在第一个元素上生成悬停效果down arrow key。不知何故,我的努力没有奏效。

我到目前为止尝试的代码如下:

JS小提琴

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:解决方案应该是跨浏览器(IE8+)

4

1 回答 1

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');
});

演示:小提琴

于 2013-04-20T12:21:36.197 回答