我可以在第二次触发事件时执行一组不同的代码吗

Can I execute a different set of code on the second time an event is triggered?

本文关键字:一组 代码 第二次 事件 执行 我可以      更新时间:2023-09-26

我正在尝试开发一个可以从箭头键导航的菜单,但在弄清楚"突出显示"第一个元素的初始事件触发器的位置时遇到了一些问题。如果你检查一下我的小提琴,你会发现当按下右箭头键时,第一个元素会高亮显示(记得点击小提琴的主体部分。

$(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');
    }
  }

试试看https://jsfiddle.net/1kf34rdq/11/

需要的某些标志

$(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;
        }
       }
     });
});