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. One of the <div>s contains a <form> which, using jQuery, will keep the border if an input within it has focus. This works perfectly except that IE6 does not support :hover on any elements other than <a>s. So, for this browser only we are using jQuery to mimic CSS :hover using the $(#element).hover() method. 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.

我在想我们可以用一些条件来阻止这种行为。例如,如果我们在鼠标移出时测试任何输入是否有焦点,我们可以阻止边界消失。AFAIK,在jQuery中没有:focus选择器,所以我不确定如何做到这一点。什么好主意吗?


当前回答

如果有人关心,现在有一个更好的方法来捕获焦点,$(foo).focus(…)

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

其他回答

使用类来标记元素状态的替代方法是内部数据存储功能。

附注:您可以使用data()函数存储布尔值和任何您想要的值。这不仅仅是关于字符串:)

$("...").mouseover(function ()
{
    // store state on element
}).mouseout(function ()
{
    // remove stored state on element
});

然后就是访问元素状态的问题了。

如果有人关心,现在有一个更好的方法来捕获焦点,$(foo).focus(…)

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

没有专注,但有选择 http://docs.jquery.com/Selectors/selected

但是如果你想要根据所选择的内容来改变事物的外观,你可能应该使用模糊事件。

http://docs.jquery.com/Events/blur

跟踪这两个状态(悬停,聚焦)作为真/假标志,当其中一个发生变化时,运行一个函数,如果两者都为假,则删除边界,否则显示边界。

onfocus sets focused = true, onblur sets focused = false。Onmouseover sets hovers = true, onmouseout sets hovers = false。在每个事件之后运行一个添加/删除边框的函数。

有一个插件可以检查一个元素是否被聚焦:http://plugins.jquery.com/project/focused

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