使用jQuery测试输入是否具有焦点

符风畔
2023-12-01

本文翻译自:Using jQuery to test if an input has focus

On the front page of a site I am building, several <div> s use the CSS :hover pseudo-class to add a border when the mouse is over them. 在我正在构建的站点的首页上,几个<div>使用CSS :hover伪类在:hover时添加边框。 One of the <div> s contains a <form> which, using jQuery, will keep the border if an input within it has focus. 其中一个<div>包含一个<form> ,使用jQuery,如果其中的输入具有焦点,它将保持边界。 This works perfectly except that IE6 does not support :hover on any elements other than <a> s. 这完全有效,除了IE6不支持:hover在除<a>的任何元素上。 So, for this browser only we are using jQuery to mimic CSS :hover using the $(#element).hover() method. 所以,对于这个浏览器,我们只使用jQuery来模仿CSS :hover使用$(#element).hover()方法:hover The only problem is, now that jQuery handles both the form focus() and hover() , when an input has focus then the user moves the mouse in and out, the border goes away. 唯一的问题是,现在jQuery处理表单focus() hover() ,当输入具有焦点然后用户移入和移出鼠标时,边框消失。

I was thinking we could use some kind of conditional to stop this behavior. 我以为我们可以使用某种条件来阻止这种行为。 For instance, if we tested on mouse out if any of the inputs had focus, we could stop the border from going away. 例如,如果我们测试鼠标输出是否有任何输入有焦点,我们可以阻止边界消失。 AFAIK, there is no :focus selector in jQuery, so I'm not sure how to make this happen. AFAIK,没有:focus jQuery中的:focus选择器,所以我不确定如何实现这一点。 Any ideas? 有任何想法吗?


#1楼

参考:https://stackoom.com/question/43aK/使用jQuery测试输入是否具有焦点


#2楼

There is a plugin to check if an element is focused: http://plugins.jquery.com/project/focused 有一个插件可以检查元素是否聚焦: http//plugins.jquery.com/project/focused

$('input').each(function(){
   if ($(this) == $.focused()) {
      $(this).addClass('focused');
   }
})

#3楼

if anyone cares there is a much better way to capture focus now, $(foo).focus(...) 如果有人关心现在有一个更好的方法来捕捉焦点, $(foo).focus(...)

http://api.jquery.com/focus/ http://api.jquery.com/focus/


#4楼

jQuery 1.6+ jQuery 1.6+

jQuery added a :focus selector so we no longer need to add it ourselves. jQuery添加了一个:focus选择器,所以我们不再需要自己添加它。 Just use $("..").is(":focus") 只需使用$("..").is(":focus")

jQuery 1.5 and below jQuery 1.5及以下版本

Edit: As times change, we find better methods for testing focus, the new favorite is this gist from Ben Alman : 编辑:随着时代的变迁,我们找到了更好的方法来测试焦点,最受欢迎的是Ben Alman的这个要点

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

Quoted from Mathias Bynens here : 从马蒂亚斯Bynens引用在这里

Note that the (elem.type || elem.href) test was added to filter out false positives like body. 请注意,添加了(elem.type || elem.href)测试以过滤掉像body这样的误报。 This way, we make sure to filter out all elements except form controls and hyperlinks. 这样,我们确保过滤掉除表单控件和超链接之外的所有元素。

You're defining a new selector. 你正在定义一个新的选择器。 See Plugins/Authoring . 请参阅插件/编写 Then you can do: 然后你可以这样做:

if ($("...").is(":focus")) {
  ...
}

or: 要么:

$("input:focus").doStuff();

Any jQuery 任何jQuery

If you just want to figure out which element has focus, you can use 如果你只是想弄清楚哪个元素有焦点,你可以使用

$(document.activeElement)

If you aren't sure if the version will be 1.6 or lower, you can add the :focus selector if it is missing: 如果您不确定版本是否为1.6或更低版本,则可以添加:focus选择器(如果缺少):

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

#5楼

April 2015 Update 2015年4月更新

Since this question has been around a while, and some new conventions have come into play, I feel that I should mention the .live method has been depreciated. 由于这个问题已经存在了一段时间,并且一些新的约定已经发挥作用,我觉得我应该提到.live方法已被折旧。

In its place, the .on method has now been introduced. 取而代之的是,现在已经引入了.on方法。

Their documentation is quite useful in explaining how it works; 他们的文档在解释它是如何工作时非常有用;

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object. .on()方法将事件处理程序附加到jQuery对象中当前选定的元素集。 As of jQuery 1.7, the .on() method provides all functionality required for attaching event handlers. 从jQuery 1.7开始,.on()方法提供了附加事件处理程序所需的所有功能。 For help in converting from older jQuery event methods, see .bind(), .delegate(), and .live(). 有关从旧的jQuery事件方法转换的帮助,请参阅.bind(),. delegate()和.live()。

So, in order for you to target the 'input focused' event, you can use this in a script. 因此,为了使您能够定位“输入聚焦”事件,您可以在脚本中使用它。 Something like: 就像是:

$('input').on("focus", function(){
   //do some stuff
});

This is quite robust and even allows you to use the TAB key as well. 这非常强大,甚至允许您使用TAB键。


#6楼

Here's a more robust answer than the currently accepted one: 这是一个比目前接受的答案更强大的答案:

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

Note that the (elem.type || elem.href) test was added to filter out false positives like body . 请注意,添加了(elem.type || elem.href)测试以过滤掉像body这样的误报。 This way, we make sure to filter out all elements except form controls and hyperlinks. 这样,我们确保过滤掉除表单控件和超链接之外的所有元素。

(Taken from this gist by Ben Alman .) (取自Ben Alman的 这个要点 。)

 类似资料: