首頁 > web前端 > js教程 > 主體

如何使用 jQuery 檢查輸入是否有焦點?

Patricia Arquette
發布: 2024-11-15 03:22:02
原創
389 人瀏覽過

How to Check if an Input Has Focus Using jQuery?

Using jQuery to Test if an Input Has Focus

This dilemma arises when using jQuery to replicate CSS :hover behavior for elements other than in IE6. The border surrounding the

disappears when an input within the form gains focus and the mouse cursor hovers in and out.

To address this, jQuery can be used to check if any input within the form has focus. However, as jQuery lacks a :focus selector, alternative methods must be employed.

jQuery 1.6+

With jQuery 1.6 and above, a :focus selector is available. The following code can be used to check for focus:

$("..").is(":focus")
登入後複製

jQuery 1.5 and Below

For earlier jQuery versions, the following code can be used to define a new selector and check for focus:

jQuery.expr[':'].focus = function(elem) {
  return elem === document.activeElement && (elem.type || elem.href);
};
登入後複製

Alternatively, you can check which element has focus using:

$(document.activeElement)
登入後複製

For All jQuery Versions

To ensure compatibility with different jQuery versions, you can add the :focus selector as follows:

(function ($) {
  var filters = $.expr[":"];
  if (!filters.focus) {
    filters.focus = function(elem) {
      return elem === document.activeElement && (elem.type || elem.href);
    };
  }
})(jQuery);
登入後複製

By testing for focus, the border can be prevented from disappearing when an input gains focus and the cursor hovers in and out.

以上是如何使用 jQuery 檢查輸入是否有焦點?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板