JavaScript 能用 div 類重點關注某個元素,但不能用 div id 宣告來重點關注
您可以使用 focus() 的概念。以下為 JavaScript 程式碼 −
例子
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> </head> <body> <span class="TEXT_FOCUS" tabindex="-1"><center>TEXT BOX FOR FOCUS</center></span><br> <button id="focusButton">click me to get the tab on focus</button> <script> document.getElementById('focusButton').addEventListener('click', function() { document.querySelectorAll('.TEXT_FOCUS')[0].focus(); }); </script> </body> </html>
要執行上述程式,請儲存檔名 anyName.html(index.html),然後右鍵單擊檔案並在 VS 程式碼編輯器中選擇即時伺服器開啟選項。
輸出
當您單擊按鈕時,焦點將放在某個元素上。快照如下 −
廣告