javascript - 在按钮上单击 JavaScript 中的焦点输入

标签 javascript html

我正在尝试在单击按钮时自动对焦 输入,但它不起作用。可以在此处找到代码进行编辑: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>

最佳答案

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

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

工作代码:

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

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

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

关于javascript - 在按钮上单击 JavaScript 中的焦点输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49475935/

相关文章:

javascript - Bootstrap 日期时间选择器中的分钟不工作

html - 调整盒模型布局

html - 我正在使用 “@media print” 打印我的 html 页面。在这里,我遇到了模型框不可见背景颜色的问题

javascript - Colspan修改依赖CSS3 @media Query

javascript - (Android) 如何在允许用户更新密码之前进行对话询问用户当前密码?

Javascript HighCharts 解析 CSV

javascript - 通过 JavaScript 将 php 变量传递到另一个 php 页面

javascript - 从 Angular $locationProvider 中的 url 中删除 # 后出现问题

javascript - 对于某些情况,如 Internet Explorer 特定的 CSS 或 Internet Explorer 特定的 JavaScript 代码,如何仅针对 Internet Explorer 10?

html - 窗口宽度减小时如何使div消失?