[英]Can I execute a different set of code on the second time an event is triggered?
我正在尝试开发一个可以从箭头键导航的菜单,并且在查找从“突出显示”第一个元素的初始事件触发器的位置时遇到一些麻烦。 如果你看看我的小提琴,你会发现第一个元素突出显示按下右箭头键时应该突出显示(记得单击小提琴的正文部分!),但我不知道从哪里去这样,随后的按键将循环遍历所有元素。
$(document).ready(function($) { $("body").keydown(function(event) { if (event.which == 39) { $(".a").css({ "outline": "3px solid red" }); } }); });
.tile { width: 100px; height: 100px; outline: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="tile a"> A </div> <div class="tile b"> B </div> <div class="tile c"> C </div>
任何提示和反馈都是值得赞赏的,即使代码处于完全不同的方向!
您应该处理所有方向键事件,如下所示:
$(document).ready(function($) { var activeIndex = -1; $(".tile").hover( function() { $(this).css({ "outline": "3px solid red" }); }, function() { $(this).css({ "outline": "1px solid red" }); } ); $("body").keydown(function(event) { if (event.which == 39) { activeIndex = 0; } else if (event.which == 38 && activeIndex != -1) { activeIndex--; } else if (event.which == 40 && activeIndex != -1) { activeIndex++; } if (activeIndex < 0) { activeIndex = 0; } else if (activeIndex == $("#menu-container").children(".tile").length) { activeIndex = $("#menu-container").children(".tile").length - 1; } if (activeIndex != -1) { $("#menu-container").children(".tile").css({ "outline": "1px solid red" }); $("#menu-container").children(".tile").eq(activeIndex).css({ "outline": "3px solid red" }); } }); });
.tile { width: 100px; height: 100px; outline: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="menu-container"> <div class="tile a"> A </div> <div class="tile b"> B </div> <div class="tile c"> C </div> </div>
按下箭头时,您可以检查当前活动的菜单项,删除其高级样式并将其添加到下一个项目。
像这样:
if (event.which == 39) {
var active_title = $('.tile.active');
active_title.removeClass('active');
if ( active_title.length && active_title.next().length) {
active_title.next().addClass('active');
} else {
$('.a').addClass('active');
}
}
需要一些标志
$(document).ready(function($) {
var arrowPressed = false;
$("body").keydown(function(event){
if (event.which == 39) {
if( !arrowPressed ) {
$(".a").css({"outline":"3px solid red"});
arrowPressed = true;
}
else {
$(".a").css({"outline":"none"});
arrowPressed = false;
}
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.