IF ELSE Hover 语句仅适用于第二次悬停
我有一个菜单,当您将鼠标悬停在图像上时,图像会发生变化,除非图像附加了活动类。我的问题是图像仅在第二次滚动时发生变化,而不是第一次时发生变化。任何想法为什么会这样。
$("#contact").hover(function () {
if ($("#contact").is(".active")) {
$("#contact img").attr("src","Images/Menu/contact_hover.png" )
}
else {
$("#contact").hover(function () {
$("#contact img").attr("src","Images/Menu/contact_hover.png" )
},
function() {
$("#contact img").attr("src","Images/Menu/contact.png" )
});
}
});
I have a menu, that when you roll over the image the image changes, unless the image has an active class attached. My problem is that the image only changes on the SECOND ROLL OVER not the FIRST. Any ideas why this is.
$("#contact").hover(function () {
if ($("#contact").is(".active")) {
$("#contact img").attr("src","Images/Menu/contact_hover.png" )
}
else {
$("#contact").hover(function () {
$("#contact img").attr("src","Images/Menu/contact_hover.png" )
},
function() {
$("#contact img").attr("src","Images/Menu/contact.png" )
});
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你不应该用 jQuery 来做这件事,真的没有必要。请阅读 CSS Image sprites 并使用 css悬停选择器,如下所示:
执行此操作要更改您使用的图像精灵的背景位置,如果您很懒,您可以完全更改图像,而不必担心精灵。您会发现此方法页面尺寸更小,兼容性也更好。
You shouldn't be doing this with jQuery, there really is no need. Please read up on CSS Image sprites and use the css hover selector like this:
Do this to change the background position of the image sprite you use, if you're lazy you could change the image altogther instead of bothering with sprites. You will find this method much lighter page size, as well as compatibility.
这是因为在 else 块第一次运行之前,您不会第二次调用
hover
。在$(document).ready
中设置所有事件处理程序,然后就可以开始了。It's because you aren't making the second call to
hover
until the else-block runs the first time. Set all of you event handlers up in$(document).ready
, and you should be good to go.你应该简化你的代码 - 试试这个
you should simplify your code - try this
工作示例位于: http://jsfiddle.net/HNGMT/
**该示例使用两个 div 来演示具有
active
类和不具有active
类的区别。课程的 HTML 也仅用于演示目的。contact
类的 jQuery 选择器将被修改以反映 id 选择器。HTML:
JavaScript:
Working example at: http://jsfiddle.net/HNGMT/
**The example uses two divs to demonstrate the difference between one with the class of
active
and one without. The HTML of cours is solely for demonstration purposes as well. And the jQuery selector for thecontact
class would be modified to reflect the id selector.HTML:
JavaScript: