【问题标题】:Hover using arrow keys使用箭头键悬停
【发布时间】:2023-07-30 08:00:01
【问题描述】:

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

目前我尝试的代码如下:

JS Fiddle

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+)

【问题讨论】:

  • 为什么需要鼠标事件?为什么不直接切换课程?
  • @charlietfl 我不太擅长 jquery。我希望你说的和 arunPjohny 在他下面的帖子中提到的一样。现在工作正常。 (虽然没有在 IE 中检查)。

标签: javascript jquery css cross-browser


【解决方案1】:

试试

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

【讨论】:

  • 您好,您的解决方案运行良好。但是刚才我意识到焦点仍然在 textarea 上,尽管悬停发生在 lielements.and 甚至滚动条也没有下降。请查看此link 以获得更好的理解。