jQuery 事件 focus() 方法



jQuery 的 focus() 事件方法用於將事件處理程式附加到 focus 事件或在選定的元素上觸發該事件。當元素獲得焦點時,無論是透過滑鼠點選還是透過選項卡導航,都會發生 focus 事件。

語法

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

$(selector).focus(function)

引數

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

  • function - 當 focus 事件發生時要執行的可選函式。

返回值

此方法沒有返回值。

示例 1

以下程式演示了 jQuery 事件 focus() 方法的使用:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Click on the below button to highlight this text.</p>
    <button>Focus on above text</button>
    <script>
        $('button').focus(function(){
            $('p').css("color", "red");
        });
    </script>
</body>
</html>

輸出

以上程式顯示一條訊息和一個按鈕。當點選按鈕時,文字顏色更改為“紅色”:


當用戶點選顯示的按鈕時:


示例 2

input 欄位獲得焦點時突出顯示它。

以下是 jQuery 事件 focus() 方法的另一個示例。我們使用此方法將焦點設定到輸入欄位:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
</head>
<body>
    <p>Click on the below input field to get focused.</p>
    <label for="">Enter your name: </label>
    <input type="text" placeholder="Name">
    <script>
        $('input').focus(function(){
            $(this).css({"background-color":"green", "color":"white"});
        });
    </script>
</body>
</html>

輸出

執行程式後,將顯示一個輸入欄位。當用戶點選此輸入欄位時,它將獲得焦點:


當用戶點選輸入欄位時:


示例 3

在不使用 function 引數的情況下使用 focus() 方法。

在下面的示例中,我們使用了 jQuery 的 focus() 事件方法,而沒有指定函式。當程式執行時,輸入欄位將自動獲得焦點:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<style>
    input{
        width: 200px;
        padding: 10px 10px;
    }
</style>
</head>
<body>
    <label for="">Enter your name: </label>
    <input type="text" placeholder="Name">
    <script>
      $('input').focus();
    </script>
</body>
</html>

輸出

執行上述程式後,它顯示一個獲得焦點的輸入欄位:


jquery_ref_events.htm
廣告