【问题标题】:Focus Input Box On Key Pressed按下按键时的焦点输入框
【发布时间】:2016-07-02 14:28:18
【问题描述】:

我已经创建了一个实时搜索,我希望当用户点击 ESC 时它应该专注于输入框并自动删除其内容(如果不是空的)。

我可以删除内容,但它不会专注于按键。

当我在window.onload 上使用focus(); 函数时,它会起作用

我有现有的代码:(也尝试了评论中的代码,感谢Focus Input Box On LoadJavaScript set focus to HTML form element

var aramaAlani = document.getElementById("id_arama");

$( document ).on( 'keydown', function ( e ) {
    if ( e.keyCode === 27 ) { //ESC key code
        aramaAlani.reset();
        aramaAlani.focus();     
        //aramaAlani.scrollIntoView();
        //document.forms[ 'id_arama' ].elements[ _element ].focus();
        //document.getElementById("id_search").focus();
    }
});

有没有什么具体的方法可以让关键事件聚焦到元素上?

【问题讨论】:

  • $(document) 检查此项并添加 id 或类或元素
  • 这个脚本是在head还是在body底部?
  • @MoshFeu 它位于head
  • 所以,你需要把它移到body底部,或者用$(document).ready包裹起来。这个问题的更多信息:stackoverflow.com/questions/14328449/…
  • @MoshFeu,感谢您的及时回复。我试图移动它或用$(document).ready 包裹它,但它不起作用。

标签: javascript html onfocus


【解决方案1】:

你不能在input上调用clear函数。

你有两个选择:

清除特定输入使用input.value = '';

像这样:

<body>
  <input type="text" id="id_arama" />
  <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <script>
    var form = document.querySelector('form');
    var aramaAlani = document.getElementById("id_arama");

    $( document ).on( 'keydown', function ( e ) {
      if ( e.keyCode === 27 ) { //ESC key code
        //form.reset();
        aramaAlani.value = '';
        aramaAlani.focus();     
        //aramaAlani.scrollIntoView();
        //document.forms[ 'id_arama' ].elements[ _element ].focus();
        //document.getElementById("id_search").focus();
      }
    });
  </script>
</body>

或者您可以使用方法reset(),但您只能在form 元素上调用它。此解决方案的优点是如果您想清除许多输入。

像这样:

<body>
  <form>
    <input type="text" id="id_arama" />
  </form>
  <script src="https://code.jquery.com/jquery-2.1.4.js"></script>
  <script>
    var form = document.querySelector('form');
    var aramaAlani = document.getElementById("id_arama");

    $( document ).on( 'keydown', function ( e ) {
      if ( e.keyCode === 27 ) { //ESC key code
        form.reset();
        aramaAlani.focus();     
        //aramaAlani.scrollIntoView();
        //document.forms[ 'id_arama' ].elements[ _element ].focus();
        //document.getElementById("id_search").focus();
      }
    });
  </script>
</body>

【讨论】:

  • 感谢您的精彩解释。我的一切都一样,但它仍然无法在我的身上工作。我在&lt;form&gt; 之后用&lt;fieldset&gt; 覆盖了我的&lt;input&gt;。我必须更新 querySelector 吗?
  • 不.. querySelector 也应该涵盖它。你能用你的代码创建一个工作的 sn-p 或 bin,以便我可以尝试了解它有什么问题吗?
  • 这是完整版:jsfiddle.net/k7a7suj9,不包括搜索 javascript 端,因为它由于某种原因在 jsfiddle 上不起作用。
  • 我修好了小提琴。有 jquery 引用问题。此外,您将输入的 id id_arama 更改为 ``。 jsfiddle.net/k7a7suj9/2
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多