【问题标题】:How do I trigger ESC button to clear text entered in text box?如何触发 ESC 按钮以清除在文本框中输入的文本?
【发布时间】:2018-06-04 11:51:39
【问题描述】:
   <input type="text" id="search" size="25" autocomplete="off"/>

我知道这是与

onkeydown="if (event.keyCode == 27)

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    声明一个按键被按下时调用的函数:

    function onkeypressed(evt, input) {
        var code = evt.charCode || evt.keyCode;
        if (code == 27) {
            input.value = '';
        }
    }
    

    以及对应的标记:

    <input type="text" id="search" size="25" autocomplete="off" 
           onkeydown="onkeypressed(event, this);" />
    

    【讨论】:

    • 效果很好,非常感谢您的帮助达林 - 我真的很感激 :)
    • 达林 - 如果你也帮我解决这个问题:stackoverflow.com/questions/3615351/… 那太好了!
    • Darin:对于 keydown 事件,它总是keyCode。所有主流浏览器都有keyCode,因此无需检查charCode,无论如何在所有当前浏览器中它都是零或未定义。
    【解决方案2】:
    <input type="text" value="" onkeyup="if ( event.keyCode == 27 ) this.value=''" />
    

    这应该可行。

    【讨论】:

      【解决方案3】:
      function keyPressed(evt) {
       if (evt.keyCode == 27) {
          //clear your textbox content here...
          document.getElementById("search").value = '';
       }
      }
      

      然后在你的输入标签中...

      <input type="text" onkeypress="keyPressed(event)" id="search" ...>
      

      【讨论】:

      • 感谢您的帮助Mamoo!
      • onkeypress 不检测转义、shift、箭头键等。必须是onkeydownonkeyup
      【解决方案4】:

      $('input[type=text]').each(function (e) {
          $(this).keyup(function (evt) {
              var code = evt.charCode || evt.keyCode;
              if (code == 27) {
                  $(this).val('');
              }
          })
      })
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <input type="text" autofocus value="input data" placeholder="ESC button clear" style="padding:5px;">
      <p>Hit esc button to see result</p>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-23
        • 2014-05-25
        • 2018-09-20
        • 1970-01-01
        • 2012-11-09
        • 1970-01-01
        • 2016-03-24
        • 1970-01-01
        相关资源
        最近更新 更多