【问题标题】:The first key is not being recorded by keypress event按键事件未记录第一个键
【发布时间】:2020-05-30 01:41:00
【问题描述】:

keypress 和 keydown 事件没有记录第一个 keypress/down 字符,而 keyup 事件工作正常,在我的情况下我需要使用 keypress 但它没有记录第一个字符

const demo = document.querySelector('.demo');
  const input = document.querySelector('.input');

  input.addEventListener('keypress', (e)=>{
    demo.innerHTML = input.value;
  });
<h1 class="demo"></h1>
<input type="text" class="input" placeholder="write something">

【问题讨论】:

    标签: javascript


    【解决方案1】:

    Document: keypress event

    已弃用

    不再推荐使用此功能。尽管某些浏览器可能仍然支持它,但它可能已经从相关的 Web 标准中删除,可能正在被删除,或者可能仅出于兼容性目的而保留。避免使用它,并尽可能更新现有代码;请参阅本页底部的兼容性表以指导您的决定。请注意,此功能可能随时停止工作。

    改用HTMLElement: input event

    const demo = document.querySelector('.demo');
    const input = document.querySelector('.input');
    
    input.addEventListener('input', (e)=>{
      demo.innerHTML = input.value;
    });
    <h1 class="demo"></h1>
    <input type="text" class="input" placeholder="write something">

    如果您想检测按下了哪个键,请使用Document: keyup event

    释放键时会触发keyup 事件。

    const demo = document.querySelector('.demo');
    const input = document.querySelector('.input');
    
    input.addEventListener('keyup', (e)=>{
      console.log(e.code);
      demo.innerHTML = input.value;
    });
    <h1 class="demo"></h1>
    <input type="text" class="input" placeholder="write something">

    【讨论】:

    • 值得一提的是,新开发人员经常忘记复制粘贴(比如用鼠标),它永远不会触发按键事件,而输入事件将涵盖所有场景。
    • 如何检测输入事件是否按下了回车键?
    • @KyleTech,在这种情况下,您应该使用keyup 事件,请查看更新后的答案:)
    【解决方案2】:

    这是因为在字段更改其值之前触发了keypress 事件,而在之后触发了keyup 事件

    所以当你检测到第一次按键时,当你更新demo元素时输入的值仍然是空的

    【讨论】:

      【解决方案3】:

      这完全是由于keypress 本身的行为所致。

      keypress 在您的input 的内容更新之前触发,因此当您检索input 的值时,它仍然是空的。

      相反,您可以使用keyup 事件,它会如您所愿地忠实触发:

      const demo = document.querySelector('.demo');
      const input = document.querySelector('.input');
      
      input.addEventListener('keyup', (e)=>{
        demo.innerHTML = input.value;
      });
      <h1 class="demo"></h1>
      <input type="text" class="input" placeholder="write something">

      或者,您可以利用您在 input 更新之前触发 keypress 的知识,并通过将 e.key 附加到 input 来模拟 input 的新值:

      const demo = document.querySelector('.demo');
      const input = document.querySelector('.input');
      
      input.addEventListener('keypress', (e)=>{
        demo.innerHTML = input.value + e.key;
      });
      <h1 class="demo"></h1>
      <input type="text" class="input" placeholder="write something">

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-09-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-19
        • 2021-03-16
        • 1970-01-01
        相关资源
        最近更新 更多