jQuery :focus 選擇器



:focus 選擇器用於選擇當前獲得焦點的元素。術語“焦點”指的是當前正在接收鍵盤或其他輸入裝置輸入的元素。我們可以將“焦點”應用於表單元素,例如 <input>、<textarea>、<button> 等。

語法

以下是 jQuery :focus 選擇器的語法:

$(":focus")

引數

:focus 選擇器選擇當前獲得焦點的元素。

示例 1

在以下示例中,我們使用 jQuery :focus 選擇器來選擇當前獲得焦點的元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("input").focus(function(){
                $(this).css("background-color", "yellow");
            }).blur(function(){
                $(this).css("background-color", "");
            });
        });
    </script>
</head>
<body>
    <form>
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" placeholder="Enter your name">
        <br><br>
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" placeholder="Enter your email">
    </form>
</body>
</html>

執行上述程式後,點選輸入文字欄位。當前獲得焦點的元素將以黃色背景顏色突出顯示。

示例 2

在此示例中,當文字區域獲得焦點時,我們為其應用藍色邊框,並在失去焦點時移除邊框:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("textarea").focus(function(){
                $(this).css("border", "2px solid blue");
            }).blur(function(){
                $(this).css("border", "");
            });
        });
    </script>
</head>
<body>
    <form>
        <label for="message">Message:</label>
        <textarea id="message" name="message" placeholder="Enter your message"></textarea>
    </form>
</body>
</html>

執行上述程式並點選文字區域以檢視藍色邊框。

jquery_ref_selectors.htm
廣告