jQuery focusin() 方法



jQuery 事件 focusin() 方法用於將事件處理程式繫結到 focusin 事件,該事件在元素或其內部任何元素獲得焦點時發生。

此方法支援事件冒泡,它也可以檢測父元素上的焦點事件。

語法

以下是 jQuery 事件 focusin() 方法的語法:

$(selector).focusin(function)

引數

此方法接受一個可選引數作為函式,如下所述:

  • function − 一個可選函式,在 focusin 事件發生時執行。

返回值

此方法不返回值,而是將事件處理程式繫結到 focusin 事件。

示例 1

當“div”元素獲得焦點時,更改其背景顏色:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    div{
        width: 30%;
        padding: 10px;
        border: 1px solid red;
    }
    input{
        width: 70%;
    }
</style>
</head>
<body>
    <div>
        <p>Change the bachground color, when gains the focus.</p>
        <label for="">Name:</label>
        <input type="text">
    </div>
    <script>
       $("div").focusin(function() {
        $(this).css({"background-color":"green", "color":"white"});
    });
    </script>
</body>
</html>

輸出

上面的程式顯示一個包含輸入欄位的 div 框,當用戶單擊輸入欄位時,div 元素的背景顏色會更改為藍色:


當用戶點選輸入欄位時:


示例 2

使用 focusin() 方法進行事件冒泡。

在下面的示例中,jQuery 事件 focusin() 方法用於事件冒泡:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<style>
    div{
        width: 200px;
        height: 100px;
        border: 2px solid black;
        text-align: center;
        align-items: center;
        justify-content: center;
        display: flex;
    }
</style>
<body>
    <p>Click on the input filed to perform the event bubbling.</p>
    <div id="parent">
        <input type="text" id="child">
    </div>
    <script>
        $('#parent').focusin(function(){
            alert("Focused on the parent element or one of its children!")
        });
        $("#child").focusin(function(){
            alert("Child element gained focus");
        });
    </script>
</body>
</html>

輸出

執行程式後,如果您聚焦於子輸入元素,由於事件冒泡,兩個 focusin() 事件處理程式都將被觸發。首先,子元素的處理程式將執行,然後是父元素的處理程式,這是因為 DOM 中的事件傳播:


如果使用者單擊輸入欄位(子元素):


單擊“確定”按鈕後,將執行父處理程式:


示例 3

無需可選 function 引數使用 focusin() 方法:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <input type="text" placeholder="Name">
    <script>
        $('input').focusin().css({"background-color":"gray", "color":"white"});
    </script>
</body>
</html>

輸出

執行程式後,未獲得焦點的輸入欄位顯示為灰色背景:


jquery_ref_events.htm
廣告
© . All rights reserved.