본문 바로가기
카테고리 없음

키보드 버튼 입력

by pishio 2025. 6. 2.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <title>Keyboard Navigation Example</title>
  <style>
    .container {
      display: flex;
      flex-direction: column;
      gap: 10px;
      margin: 50px;
    }
    .card {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 10px;
      border: 1px solid #ccc;
    }
    button {
      padding: 5px 10px;
    }
    button:focus {
      outline: 2px solid blue;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="card">
      <span>Name 1</span>
      <button class="action" data-row="0" data-col="0">Success</button>
      <button class="action" data-row="0" data-col="1">Fail</button>
    </div>
    <div class="card">
      <span>Name 2</span>
      <button class="action" data-row="1" data-col="0">Success</button>
      <button class="action" data-row="1" data-col="1">Fail</button>
    </div>
    <div class="card">
      <span>Name 3</span>
      <button class="action" data-row="2" data-col="0">Success</button>
      <button class="action" data-row="2" data-col="1">Fail</button>
    </div>
  </div>

  <script>
    const buttons = document.querySelectorAll('.action');
    const totalRows = 3;
    const totalCols = 2;

    let currentRow = 0;
    let currentCol = 0;

    function focusButton(row, col) {
      const btn = document.querySelector(`button[data-row="${row}"][data-col="${col}"]`);
      if (btn) {
        btn.focus();
      }
    }

    // 초기 포커스 설정
    focusButton(currentRow, currentCol);

    document.addEventListener('keydown', (e) => {
      if (e.key === 'ArrowRight') {
        currentCol = (currentCol + 1) % totalCols;
      } else if (e.key === 'ArrowLeft') {
        currentCol = (currentCol - 1 + totalCols) % totalCols;
      } else if (e.key === 'ArrowDown') {
        currentRow = (currentRow + 1) % totalRows;
      } else if (e.key === 'ArrowUp') {
        currentRow = (currentRow - 1 + totalRows) % totalRows;
      } else if (e.key === 'Enter') {
        currentRow = (currentRow + 1) % totalRows;
      }

      focusButton(currentRow, currentCol);
    });
  </script>
</body>
</html>

댓글