jyd焦点搜索表单在keydown? (问号)

时间:2017-03-29 06:58:52

标签: javascript jquery twitter-bootstrap search input

当使用Javascript按下这两个键时,如何关注搜索表单输入字段?

shift + / 会生成

所以基本上,在问号的keydown上,搜索表单会自动聚焦。

这是我目前的bootstrap 3搜索表单代码:

<form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">
    <div class="form-group">
        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">
    </div>
    <button type="submit" class="btn btn-default"></button>
</form>

4 个答案:

答案 0 :(得分:2)

尝试

$(document).on('keypress',function(e){
   if(e.keyCode == 63 ) {
      $("#inputMessage").focus()
   }
});

答案 1 :(得分:1)

检查此代码。

创建一个对象来存储按键并添加一个eventListener,它将每个按键添加到Object。

然后检查keyCodes Shift (16)和 / (191)

var map = {}; //to store the keycodes
onkeydown = onkeyup = function(e){
    e = e || event;
    
    map[e.keyCode] = e.type == 'keydown';
    
    if(map["16"]==true && map["191"]==true){  // 16 => shift and 191 /
      e.preventDefault();
      var elm=document.getElementById('inputMessage');
      elm.focus();
      
    }
    /* insert conditional here */
}
<form class="navbar-form navbar-right" role="form" method="post" action="{$WEB_ROOT}/knowledgebase.php?action=search">
    <div class="form-group">
        <input id="inputMessage" class="form-control" placeholder="Search website.com" type="text" name="search">
    </div>
    <button type="submit" class="btn btn-default"></button>
</form>

答案 2 :(得分:1)

这项工作。您必须将事件e.shiftKey/按钮的键码一起使用(我使用219,因为它是意大利语键盘布局中的?位置)

&#13;
&#13;
$(document).on('keydown', function(e){
  if(e.shiftKey && e.keyCode == 219)
  {
    $("#search").focus();
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="search">
&#13;
&#13;
&#13;

答案 3 :(得分:0)

这有效,但也许你建议更清洁的解决方案?

<script type="text/javascript">
$(document).keyup('keyup', function(event){
    if(event.which === 191) {
        $('#inputMessage').focus();
    }
});
</script>

也许它不应该是 keyup ,或者焦点可能不是最好的。怎么想?我正在寻找获得成果的绝对优越方式。