gpt4 book ai didi

javascript - 如何添加类(class)并让 children 专注于按键功能

转载 作者:太空宇宙 更新时间:2023-11-03 20:41:39 25 4
gpt4 key购买 nike

标记

<ul class="focus">
<li class="active"><a>Text 1</a></li>
<li><a>Text 2</a></li>
<li><a>Text 3</a></li>
<li><a>Text 4</a></li>
<li><a>Text 5</a></li>
<li><a>Text 6</a></li>
<li><a>Text 7</a></li>
<li><a>Text 8</a></li>
<li><a>Text 9</a></li>
<li><a>Text 10</a></li>
<li><a>Text 11</a></li>
<li><a>Text 12</a></li>
</ul>

CSS

.focus{
height:60px;
list-style-type:none;
overflow:auto;
}
.focus li a {
}
.focus li.active{
background:#f6f6f6;
}

JQUERY

$( ".focus" ).keydown(function() {
if ( KeyCode == 40 ) {
$(this).next(li).addClass('active').children(a).focus();
});

对于此标记,我需要在按下向下箭头时向子 li 添加一个事件类,并且事件 li 需要获得焦点。我不知道如何进一步破解代码,谁能解释一下。提前致谢。

DEMO

最佳答案

Demo Fiddle

你应该添加一个 tabindexul ( <ul class="focus" tabindex='0'> ), 和 href a 的属性,然后使用以下内容:

$(".focus").keydown(function (e) {
if (e.keyCode == 40) {
$('.active').removeClass('active').next('li').addClass('active').children('a').focus();
}
});

删除 ul 上的轮廓(Chrome)当它有焦点时,您可以使用 CSS:

.focus:focus, .focus:active{
outline:none;
}

添加 tabindex允许 ul可选择和 key要注册的事件。请注意,您还想用语音标记将选择器括起来。


Extended Demo

您还可以使用下面的内容向上滚动/循环浏览所有元素:

$(".focus").keydown(function (e) {
if (e.which == 40) {
var next = $('.active').removeClass('active').next('li');
next = next.length > 0 ? next : $('.focus li:eq(0)');
next.addClass('active').children('a').focus();
} else if (e.which == 38) {
var prev = $('.active').removeClass('active').prev('li');
prev = prev.length > 0 ? prev : $('.focus li').last();
prev.addClass('active').children('a').focus();
}
});

关于javascript - 如何添加类(class)并让 children 专注于按键功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25114566/

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