按键上的焦点输入框 [英] Focus Input Box On Key Pressed

查看:88
本文介绍了按键上的焦点输入框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a live search, I want when user clicks on ESC it should focus to input box and remove its content if not empty automatically.

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

I am able to remove the content but it won't focus on key press.

函数 focus(); 适用于我在 window.onload上使用它

我有现有的代码:(也试过评论中的那些感谢谢谢加载焦点输入框 JavaScript将焦点设置为HTML表单元素

I have the existing code: (also tried the ones maked in comment thanks to Focus Input Box On Load, and JavaScript 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();
    }
});

关键事件是否有任何特定方法可以关注元素?

Is there any specific method for key events to focus on element?

推荐答案

您无法在输入清除函数c>。

You can't call clear function on input.

您有2个选项:

清除特定输入 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() 方法,但只能在表单元素上调用它。这个解决方案的优点是如果你想要清除许多输入。

Or you can use the method reset() but you can call it only on form element. The good point in this solution is if you want to clear many inputs.

像这样:

<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>

这篇关于按键上的焦点输入框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆