如何将箭头键绑定添加到react \ redux

时间:2018-10-04 10:31:55

标签: keyboard-events key-bindings

最后,我创建了一个游戏,它是一个3答案测验游戏,但是我希望能够使用上下键滚动浏览3个答案,即3个按钮。但是我一直在努力实现它,以前有人尝试过吗?或任何提示?

这是我要添加到我的redux中的伪代码,但是它不是很实用

<!DOCTYPE html>
<html>

<head>
  <style>
    a:focus, a:active {
    font-size: 18px;
    color: red;
    font-family: Helvetica;
    }

   .btn:focus {
     background: green;
     outline: none;
   }
</style>
</head>

<body onkeydown="myFunction(event)">

  <a id="myAnchor" href="https://www.w3schools.com">Visit W3Schools.com</a>

  <p id="demo"></p>

  <input class="btn" id="btn-1" type="button"  value="First dog">
  <input class="btn" id="btn-2" type="button"  value="Second dog">
  <input class="btn" id="btn-3" type="button"  value="Third dog">

  <script>
    window.onload = () => {
      document.getElementById("btn-1").focus();
      console.log(document.activeElement)
    };

    function myFunction(event) {
      const btn1 = document.getElementById("btn-1");
      const btn2 = document.getElementById("btn-2");
      const btn3 = document.getElementById("btn-3");

      const keyPress = event.which || event.keyCode;
      const focusedButtonElement = document.activeElement.id

      switch(focusedButtonElement) {
        case "btn-1":
          if (keyPress === 39) return btn2.focus() 
        case "btn-2":
          if (keyPress === 37) return btn1.focus() 
          if (keyPress === 39) return btn3.focus() 
        case "btn-3":
          if (keyPress === 37) return btn2.focus() 
        default:
        break
      }

      if(keyPress === 13) {
        document.activeElement.click();
        console.log("clicked")
      }

    }
  </script>

</body>

</html>

谢谢大家

1 个答案:

答案 0 :(得分:0)

从body标签中删除&Item.isActive { &::before { background: $brandColorSecondary; content: ''; display: block; width: 10px; height: 60px; } } 事件监听器,然后修改onkeydown函数以编程方式添加事件监听器。

window.onload