gpt4 book ai didi

javascript - 如何知道哪个元素在上方,哪个元素在所选元素下方?

转载 作者:太空宇宙 更新时间:2023-11-03 22:48:43 24 4
gpt4 key购买 nike

我有这样的代码(我知道它不会在 first/left 和 last/right 上工作):

$(document).keydown(function(e) {
if (e.which == 38) { // UP
} else if (e.which == 40) { // DOWN
} else if (e.which == 37) { // LEFT
$('.selected').removeClass('selected').prev().addClass('selected');
} else if (e.which == 39) { // RIGHT
$('.selected').removeClass('selected').next().addClass('selected');
}
});
ul {
width: 200px;
height: 200px;
list-style: none;
margin: 0;
padding: 0;
border: 1px solid gray;
overflow: auto;
}
li {
width: 20px;
height: 20px;
margin: 5px;
float: left;
}
li.selected {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li class="selected"></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>

如何在按下向上箭头时选择上面的元素,而当我按下向下箭头时如何选择下面的元素?

最佳答案

var $li = $('li');

function adjustSelected ( offset ) {
var $selected = $li.filter('.selected');
var currentIndex = $li.index($selected);

if ( currentIndex + offset > -1 && currentIndex + offset < $li.length ) {
$selected.removeClass('selected');
$li.eq(currentIndex + offset).addClass('selected');
}
}

$(document).keydown(function(e) {
if (e.which == 38) { // UP
adjustSelected(-6);
} else if (e.which == 40) { // DOWN
adjustSelected(6);
} else if (e.which == 37) { // LEFT
adjustSelected(-1);
} else if (e.which == 39) { // RIGHT
adjustSelected(1);
}
});
ul {
width: 200px;
height: 200px;
list-style: none;
margin: 0;
padding: 0;
border: 1px solid gray;
overflow: auto;
}
li {
width: 20px;
height: 20px;
margin: 5px;
float: left;
background: #888;
}
li.selected {
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li class="selected"></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>

关于javascript - 如何知道哪个元素在上方,哪个元素在所选元素下方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41079875/

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