[英]On button click focus input in JavaScript
我正在嘗試在按鈕單擊時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>
autofocus
是HTML屬性。 如果要通過JavaScript設置focus屬性,則必須使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.