You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过键盘方向键控制3行3列按钮组的绿色选中态按规则移动

实现方案

核心逻辑是先定位当前选中按钮的行索引和列索引,再根据按键类型计算目标按钮的位置:

  • 左右方向键:保持当前行不变,调整列索引,选中同行相邻列的按钮
  • 上下方向键:保持当前列不变,直接定位到第二行(索引为1,即中间行)同列的按钮

JavaScript部分替换为以下代码即可,原有CSS、HTML结构无需修改:

const $allRows = $('.all');
const ROW_COUNT = $allRows.length;
const COL_COUNT = $allRows.eq(0).find('button').length;
let $selectedBtn;

$(window).keydown(function(e) {
  // 阻止方向键默认滚动页面的行为
  if ([37,38,39,40].includes(e.which)) {
    e.preventDefault();
  }

  // 无选中状态时默认选中第一个按钮
  if (!$selectedBtn) {
    $selectedBtn = $allRows.eq(0).find('button').eq(0).addClass('selected');
    return;
  }

  // 计算当前选中按钮的行、列索引
  const $currentRow = $selectedBtn.closest('.all');
  const currentRowIdx = $allRows.index($currentRow);
  const currentColIdx = $currentRow.find('button').index($selectedBtn);

  let targetRowIdx = currentRowIdx;
  let targetColIdx = currentColIdx;

  switch(e.which) {
    // 左键
    case 37:
      targetColIdx = Math.max(0, currentColIdx - 1);
      break;
    // 右键
    case 39:
      targetColIdx = Math.min(COL_COUNT - 1, currentColIdx + 1);
      break;
    // 上下键 直接跳转中间行(索引1)
    case 38:
    case 40:
      targetRowIdx = 1;
      break;
  }

  // 更新选中状态
  $selectedBtn.removeClass('selected');
  $selectedBtn = $allRows.eq(targetRowIdx).find('button').eq(targetColIdx).addClass('selected');
});

内容的提问来源于stack exchange,提问作者user16388400

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 07:27:03