gpt4 book ai didi

javascript - 应用鼠标悬停样式时,通过箭头键导航删除应用于列表项的选定类

转载 作者:太空宇宙 更新时间:2023-11-04 09:46:47 24 4
gpt4 key购买 nike

当在文本框中按下向上/向下箭头键时,所选类将应用于列表项。如果我将鼠标指针移到列表项上并同时按向上/向下箭头键,则悬停和所选类都会应用于列表项。类似select input option的hover和selected class如何切换?

http://jsfiddle.net/AyAZx/790/

$('#college').keyup(function(e) {

var $listItems = $('.field-wrap li');
var key = e.keyCode,
$selected = $listItems.filter('.selected'),
$current;

$listItems.removeClass('selected');


var menu = $('#college_list');
var height = $selected.outerHeight();
var top = menu.scrollTop();
var menuHeight = menu[0].scrollHeight;

if (key == 40) // Down key
{
if (!$selected.length || $selected.is(':last-child')) {
$current = $listItems.eq(0);
menu.scrollTop(0);
} else {
$current = $selected.next();
menu.scrollTop(top + height);
}

$current.addClass('selected');
}

if (key == 38) // Up key
{
if (!$selected.length || $selected.is(':first-child')) {
$current = $listItems.last();
menu.scrollTop(menuHeight + height);
} else {
$current = $selected.prev();
menu.scrollTop(top - height);
}
$current.addClass('selected');
}

});
.field-wrap ul {
width: 93%;
margin-top: 1px;
border: 1px solid #3498DB;
position: absolute;
z-index: 9;
background: white;
list-style: none;
max-height: 100px;
overflow-y: auto;
}
.field-wrap ul li {
padding: 2px;
border: solid grey;
border-width: 0 0 2px 0;
}
.field-wrap ul li:hover {
background: #2980B9;
}
<div class="field-wrap">
<input type="text" id="college" placeholder="Name" required autocomplete="off" />
<ul id="college_list">
<li>abc</li>
<li>def</li>
<li>asdff</li>
<li>dasdf</li>
<li>asdef</li>
<li>asdf</li>
<li>asf</li>
<li>asdef</li>
</ul>
</div>

最佳答案

恐怕在这种情况下,您必须将 css :hover 替换为 mousemove 事件:

$('#college_list li').mousemove(function() {
$('.field-wrap li').removeClass('selected');
$(this).addClass('selected');
});

关于javascript - 应用鼠标悬停样式时,通过箭头键导航删除应用于列表项的选定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39430956/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com