在 JavaScript 中单击按钮焦点输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49475935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:35:50  来源:igfitidea点击:

On button click focus input in JavaScript

javascripthtml

提问by Gragas Incoming

I am trying to autofocusinput on button click but it doesn't work. Code can be found here for edit: https://www.w3schools.com/code/tryit.asp?filename=FPPCFP5RTU9E

我试图autofocus在按钮点击时输入,但它不起作用。可以在此处找到代码进行编辑:https: //www.w3schools.com/code/tryit.asp?filename=FPPCFP5RTU9E

<input type="text" id="myText" autofocus>

<button onclick="myFunction()">Focus Input</button>

<p id="demo"></p>

<script>
  function myFunction() {
      document.getElementById("myText").autofocus = true;  
  }
</script>

回答by Mamun

autofocusis an HTML attribute. If you want to set the focus property by JavaScript you have to use focus().

autofocus是一个 HTML 属性。如果你想通过 JavaScript 设置焦点属性,你必须使用focus().

So try document.getElementById("myText").focus();:

所以尝试document.getElementById("myText").focus();

Working Code:

工作代码:

function myFunction() {
     document.getElementById("myText").focus();
}
<input type="text" id="myText" autofocus>

<button onclick="myFunction()">Focus Input</button>

<p id="demo"></p>