jQuery 类更改在鼠标悬停之前不会更新
我有一个菜单,每个菜单项都是一个在 css 中设置了类的跨度:
.newClass {color: red}
.oldClass {color:black} oldClass:hover {color:blue; 当您单击菜单项时,
类将更改为: $(this).removeClass('oldClass').addClass('newClass');
效果很好。
当单击另一个菜单项时,我将类更改回当前菜单项: $(this).removeClass('newClass').addClass('oldClass');
问题是当类改回时,直到我将鼠标悬停在菜单项上时,更改才会反映出来。因此,菜单项颜色保持红色,直到我将其鼠标悬停,然后它会变回黑色并带有蓝色悬停。
请参阅评论中 Gaby 的示例,了解应该发生的情况
这是我的实际代码:
$('.headingRev').removeClass('headingRev').addClass('heading');
$(this).removeClass('heading').addClass('headingRev');
这是 css:
.heading {color: #bb1f1a;}
.heading:hover {颜色: #e9b49e;文字装饰:无;}
.headingRev {颜色:#e9b49e;}
I have a menu and each menu item is a span with a class set in css:
.newClass {color: red}
.oldClass {color:black} oldClass:hover {color:blue;}
When you click on a menu item the class is changed with:$(this).removeClass('oldClass').addClass('newClass');
which works fine.
When another menuItem is click I change the classes back on the current menu item with:$(this).removeClass('newClass').addClass('oldClass');
The problem is when the class is changed back, the change is not reflected until I mouse over the menu Item. So the menu item color stays red until I mouse it and then it changes back to black with a blue hover.
See Gaby's example in the comments for what should be happening
Here is my actual code:
$('.headingRev').removeClass('headingRev').addClass('heading');
$(this).removeClass('heading').addClass('headingRev');
and here is the css:
.heading {color: #bb1f1a;}
.heading:hover {color: #e9b49e;text-decoration:none;}
.headingRev {color: #e9b49e;}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个可能的问题可能是您从当前菜单项中删除选择的方式。
如果您从点击内部执行此操作,则不应使用
this
,因为this
会指向单击的元素,而不是之前的当前元素。如果是这种情况,那么您应该使用$('.newClass').removeClass('newClass').addClass('oldClass');
查看一些可在 http://www.jsfiddle.net/khGRW/ 运行的代码
更新
我现在明白了..您正在使用Cufon,它用图像或画布元素替换文本..
这使得它对正常的DOM更改没有响应。
将类更改为元素(当前不在
hover
事件下 ) 强制它根据 DOM 的当前状态重新绘制菜单。hover
效果会自动处理,因为它们支持该选项,但这就是 DOM 监控从 Cufon 端结束的地方。A possible problem could be the way you remove the selection from the current menu item..
you should not use
this
if you are doing it from inside the click, becausethis
would point to the clicked element, and not the previously current one.. if that is the case then you should use$('.newClass').removeClass('newClass').addClass('oldClass');
see some code that works at http://www.jsfiddle.net/khGRW/
Update
I see now.. you are using Cufon, which replaces the text with images or canvas elements..
This make it unresponsive to normal DOM changes.
You need to call the
Cufon.refresh('#content')
after changing the class to an element (that is not currently underhover
event) to force it to repaint the menu according to the current state of the DOM.The
hover
effect is taken care automatically because they support that option, but that is where the DOM monitoring ends from the Cufon side..尝试这种方法:
try this approach: