简体   繁体   English

如何聚焦隐藏的输入字段

[英]How to focus a hidden input field

I'm new to JS and trying to make an input field that that only appears when the user types anywhere on the page. 我是JS的新手,它试图创建一个仅在用户在页面上的任何地方键入时才会显示的输入字段。 Currently, the appearing of the input field works but once it's visible, the user still has to click into the field to type in it. 当前,输入字段的显示有效,但是一旦可见,用户仍然必须单击该字段以键入该字段。

I would like it to work like: 我希望它像这样工作:

  • User presses "S" 用户按下“ S”
  • Field appears with "S" typed in it. 出现带有“ S”的字段。

Any help would be much appreciated! 任何帮助将非常感激!

http://codepen.io/jeremypbeasley/pen/RNrore http://codepen.io/jeremypbeasley/pen/RNrore

var searchArea = $(".search");

searchArea.hide();

$(document).ready(function()  {

  $( "body" ).keydown(function() {
    searchArea.show();
    searchArea.elements['input'].focus();
    console.log("worked!");
  });

});

What is searchArea.elements['input'] supposed to do ? searchArea.elements['input']应该做什么?

Try it like this instead, using jQuery's find method 改用jQuery的find方法,像这样尝试

$( "body" ).on('keydown', function() {
    searchArea.show().find('input').focus();
});

PEN 钢笔

You need to find the input element within the seach area, then call focus() on it: 您需要在搜索区域内find input元素,然后在其上调用focus()

$(document).ready(function()  {
  var $searchArea = $(".search").hide();

  $("body").keydown(function() {
    $searchArea.show();
    $searchArea.find('input').focus();
  });  
});

Updated CodePen 更新的CodePen

Or just set id to input field (<input autofocus="autofocus" id="hid_inp" >) and use $("#hid_inp").focus(); 或者只是将id设置为输入字段(<input autofocus =“ autofocus” id="hid_inp" >),然后使用$("#hid_inp").focus(); instead of searchArea.elements['input'].focus();" 而不是searchArea.elements['input'].focus();"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM