jQuery 失去焦點事件


jQuery 允許開發人員編寫比 JavaScript 更易讀的程式碼。我們可以使用 jQuery 將 10 行 JavaScript 程式碼減少到 3 到 4 行。

有時,我們需要使用 jQuery 在元素失去焦點時執行某些操作。我們可以使用 jQuery 的 focusOut() 和 blur() 方法來觸發失去焦點事件。主要開發人員需要將其與輸入、複選框、單選按鈕等一起使用,以便在使用者完成輸入後向使用者提供驗證反饋。

通常,我們將 focusout() 和 blur() 方法與 focus() 方法一起使用,後者將焦點放在輸入上。

使用 FocusOut() 方法

每當輸入失去焦點時,focusOut() 方法都會執行回撥函式。它是 JavaScript 中“focusout”事件的替代方法。我們可以透過引用輸入元素來執行 focusOut() 方法。

語法

使用者可以按照以下語法使用 focusOut() 方法在元素失去焦點時執行某些操作。

$("selector").focusOut(function () {
   //Perform some action
});

在上述語法中,每當元素失去焦點時,它將執行包含 jQuery 程式碼的回撥函式。

示例 1

我們在下面的示例中建立了文字輸入並添加了“first”類。此外,我們還對輸入元素進行了樣式設定。在 jQuery 中,我們使用 focusOut() 方法在輸入失去焦點時從輸入元素中刪除“first”類。此外,我們還使用 focus() 方法在使用者將焦點放在輸入元素上時將“first”類新增到輸入元素中。

在輸出中,使用者可以單擊輸入元素以聚焦,單擊外部以從元素中移除焦點並觀察樣式的變化。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
   <style>
      .first {
         width: 300px;
         height: 50px;
         font-size: 15px;
         text-align: center;
         margin: 30px auto;
         border: 2px solid green;
         color: blue;
         border-radius: 12px;
      }
   </style>
</head>
<body>
   <h2>Using the <i> jQuery's focusOut() </i> method to trigger loose events </h2>
   <input type = "text" id = "focusOut" value = "Click outside to trigger loose event" class = "first" />
   <script>
      // using the focusOut() method to remove the 'first' class when the focus is out of the input field
      $("#focusOut").focusout(function () {
         $(this).removeClass("first");
      });
      // using the focus() method to add the 'first' class when the focus is on the input field
      $("#focusOut").focus(function () {
         $(this).addClass("first");
      });
   </script>
</body>
</html>

示例 2

在下面的示例中,我們使用 focusOut() 方法建立了電子郵件驗證器。在這裡,我們建立了一個電子郵件輸入欄位以從使用者那裡獲取電子郵件輸入。

在 jQuery 中,我們使用 focusOut() 方法在使用者單擊電子郵件輸入欄位外部時驗證電子郵件。我們使用正則表示式和 test() 方法來驗證電子郵件地址。我們根據電子郵件地址的有效性以綠色或紅色顯示訊息。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
</head>
<body>
   <h3>Using the <i> jQuery's focusOut() </i> method to validate email when input loses the focus </h2>
   <input type = "email" id = "email" value = "Enter your email" />
   <div id = "message"> </div>
   <script>
      // validating email
      $("#email").focusout(function () {
      
         // accessing value using id
         var email = $("#email").val();
         
         //If the email is empty, show an error message; Otherwise, continue with the validation
         if (email != "") {
            var regex = /^[A-Za-z0-9._]*\@[A-Za-z]*\.[A-Za-z]{2,5}$/;
            
            // validate email using test() method and regex
            if (regex.test(email)) {
               $("#message").html("Valid Email");
               $("#message").css("color", "green");
            } else {
               $("#message").html("Invalid Email");
               $("#message").css("color", "red");
            }
         } else {
            $("#message").html("Enter Email");
            $("#message").css("color", "red");
         }
      });
   </script>
</body>
</html>

使用 Blur() 方法

blur() 方法類似於 focusOut() 方法。它還在使用者單擊輸入元素外部時執行回撥函式。

語法

使用者可以按照以下語法使用 blur() 方法在元素失去焦點時執行函式。

$('#text').blur(function () {
   // js code
}); 

blur() 方法將回調函式作為引數。

示例 3

我們在下面的示例的 HTML 部分建立了文字輸入。在 JQuery 中,我們使用 blur() 方法在元素失去焦點時顯示特定訊息。此外,我們還使用 focus() 方法在元素聚焦到輸入元素上時顯示特定訊息。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
</head>
<body>
   <h3>Using the <i> jQuery's blur() </i> method to act when an element loses focus</h3>
   <input type = "text" id = "text" placeholder = "click the input">
   <br> <br>
   <div id = "message"> </div>
   <script>
      $('#text').blur(function () {
         $('#message').html('You have lost the focus.');
      });
      $('#text').focus(function () {
         $('#message').html('You have focus on the input.');
      });
   </script>
</body>
</html>

示例 4

在下面的示例中,我們建立了密碼強度驗證器。我們在密碼輸入欄位上添加了“input”事件。因此,每當使用者更改輸入值時,它都會觸發回撥函式。

在這裡,我們根據一些因素顯示密碼強度。如果密碼長度大於 8 且包含小寫字元、大寫字元和數字,則密碼非常強。如果它僅包含字母字元,則密碼為字串,依此類推。

每當使用者失去焦點時,我們都會選擇密碼強度的文字值並在網頁上顯示驗證訊息。

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"> </script>
</head>
<body>
   <h3>Using the <i> jQuery's blur() </i> method to create a password validator</h3>
   <input type = "password" id = "password" placeholder = "Enter your password...">
   <div id = "strength"> </div>
   <div id = "message"> </div>
   <script>
      $('#password').on('input', function () {
         var password = $(this).val();
         if (password.length >= 8) {
            if (password.match(/[A-Z]/) && password.match(/[a-z]/) && password.match(/[0-9]/)) {
               $('#strength').text('Very Strong');
            } else if (password.match(/[A-Z]/) && password.match(/[a-z]/)) {
               $('#strength').text('Strong');
            } else if (password.match(/[A-Z]/)) {
               $('#strength').text('Moderate');
            } else {
               $('#strength').text('Weak');
            }
         } else {
            $('#strength').text('Weak');
         }
      });
      $('#password').blur(function () {
         var strength = $('#strength').text();
         if (strength === 'Weak') {
            $('#message').html('Your password is weak. Please try again.');
         } else {
            $('#message').html('Your password is strong.');
         }
      });
   </script>
</body>
</html>

我們學習瞭如何在輸入元素失去焦點時觸發函式。我們使用 focusOut() 和 blur() 方法來實現我們的目標。blur() 和 focusOut() 方法之間的區別在於 blur() 是 DOM 特定的方法,而 focusOut() 是 jQuery 特定的方法。

更新於: 2023年5月5日

3K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告