首页 > 解决方案 > 为什么我的 JavaScript 中的“keypress”在单击 HTML 按钮后同时表现得像“keypress”和“keyup”?

问题描述

所以我正在尝试使用 html、css 和 JS 制作一个基本的“随机颜色生成器”,所有这些我都非常陌生。我想允许用户在页面上的任何位置单击按钮以生成随机颜色或按空格键以生成随机颜色。一开始按空格键就可以很好地工作,只要尚未单击按钮,但是在单击按钮后,当用户再次尝试按空格键时,空格键的作用就像按键和按键一样? ?? 这意味着在按下时会产生一种颜色,然后在释放键时会产生完全不同的颜色。这是我的 JS 代码:

const hexNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"];
const hexBtn = document.querySelector(".hexBtn");
const bodyBcg = document.querySelector("body");
const hex = document.querySelector(".hex");

bodyBcg.addEventListener('keypress', getHex);

hexBtn.addEventListener('click', getHexClick);


function getHex(e) {
  if (e.key !== ' ')
    return;

  colorGenerator();
}

function getHexClick() {
  colorGenerator();
}

function colorGenerator() {
  let hexColor = "#";

  for (let i = 0; i <= 5; i++) {
    let random = Math.floor(Math.random() * hexNumbers.length);
    hexColor += hexNumbers[random];
  }

  bodyBcg.style.backgroundColor = hexColor;
  hex.innerHTML = hexColor;
}

PS我想让用户在按下空间时触发颜色,所以只是改变不是我想要的bodyBcg.addEventListener('keypress', getHex);bodyBcg.addEventListener('keyup', getHex);任何帮助表示赞赏。

这是我的 HTML:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Color Generator</title>
    <link rel="stylesheet" href="./main.css" />
  </head>
  <body>
    <div class="container">
      <h2 class="hexColor">
        this hex color code is : <span class="hex"></span>
      </h2>
      <button type="button" class="hexBtn">Press here to change color</button>
    </div>
    <script src="./script.js"></script>
  </body>
</html>

标签: javascripthtml

解决方案


当您单击按钮元素时,按钮将获得焦点。空格键的默认动作是“单击”焦点元素以触发其动作,就像附加到按钮的单击侦听器一样。

您可以通过在点击空格时以编程方式模糊按钮来修复您的代码。

function getHex(e) {
  if (e.key !== ' ')
    return;
  hexBtn.blur();
  colorGenerator();
}

推荐阅读