关于鼠标悬停问题的简单 addClass
我正在尝试为 li 项目设置一个类,但没有成功。我已经尝试了很多事情(要发布的内容太多),但我无法弄清楚:
$("li").live("mouseover",function(){
$(this).addClass('current');
});
li 项目必须在鼠标悬停(/悬停)时更改类并保持该类状态,即使鼠标悬停在外部 > ul。但是(这是棘手的部分)如果悬停另一个 li 项目,则会丢失类。这意味着悬停的项目获得“当前”类别。
希望它有意义..这是小提琴 jsfiddle
I'm trying to set a class for a li item, with no luck. I have tried many things (to much to post) but I can't figure it out:
$("li").live("mouseover",function(){
$(this).addClass('current');
});
The li item has to change class on mouseover(/hover) and keep that class state even if the mouse hovers outside the ul. But (and this is the tricky part) lose the class if another li item is hovered. Which means that the item being hovered gets the ''current'' class.
Hope it makes some sense..This is the fiddle jsfiddle
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在将类添加到新元素之前,您应该从当前拥有该类的所有元素中删除该类:
jsFiddle
为了进行额外的优化(即保存
$('.current')
选择,这在某些较旧的浏览器中可能会很昂贵),您可以检查悬停的元素是否已经具有该类:或者,根据菲利克斯的绝妙主意,
jsFiddle
You should remove the class from all the elements that currently have it before adding it to the new element:
jsFiddle
For added optimisation (i.e. to save the
$('.current')
selection, which can be expensive in some older browsers), you could check to see if the element hovered already has the class:Or, per Felix's excellent idea,
jsFiddle
只需从其兄弟姐妹中删除该类即可:
Just remove the class from its siblings:
如果您从所有 li 元素中删除当前类,我已经在小提琴 fiddle 中为您修复了该问题然后应用它,你会有更好的运气。
I've fixed it for you in the fiddle fiddle if you remove the current class from all the li elements and then apply it, you'll have better luck.