通过 jQuery 淡入/淡出悬停
我正在尝试通过 jQuery 向按钮添加简单的淡入/淡出效果,但我有点坚持淡出。我使用这段代码:
$('#header #menu li a').hover(function () {
$(this).fadeOut(0).addClass('hover').fadeIn(300);
},
function () {
$(this).fadeOut(0).removeClass('hover').fadeIn(0);
});
它添加了一个悬停类,该类定义了 css 背景并使悬停图像淡入。但是当我将光标移出按钮时,它只是像平常一样消失,没有淡出。
你能帮我解决这个问题吗?
非常感谢所有的回复
I'm trying to add a simple fade in/out effect to the buttons by jQuery but I'm a bit stuck with fading out. I use this code:
$('#header #menu li a').hover(function () {
$(this).fadeOut(0).addClass('hover').fadeIn(300);
},
function () {
$(this).fadeOut(0).removeClass('hover').fadeIn(0);
});
It adds a hover class which defines a css background and fade the hover image in. But when I move a cursor out of the button, it simply disappears as normally, no fading out.
Can you help me with this please?
Thanks a lot for all replies
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这两个函数是相反的,所以应该可以工作...(代码已更新)
这非常难看...在 http://jsfiddle.net/zS6ex/。
但是,您仍然遇到一个问题:您正在淡入或淡出整个链接,而不仅仅是图像。据我所知,你不能单独设置背景图像不透明度(如果你手动设置完全不透明度已经很痛苦了......)
These two functions are opposites of each other, so should work... (code updated)
That's pretty ugly... See it in action on http://jsfiddle.net/zS6ex/.
However, you still have a problem: you're fading the whole link in or out, not only the image. As far as I know, you cannot set background image opacity separately (setting full opacity is already a pain if you do it manually...)
就像在 SO 上多次回答的那样,您需要使用 jQuery
fx 方法
中的回调
来执行动画完成后的任何操作。无论如何,调用
.fadeOut(0)
会淡出该元素,根本没有动画,就像即时一样。第一个参数是持续时间。http://api.jquery.com/fadeOut/
Like answered many times here on SO, you need to use the
callbacks
from jQueryfx methods
to do anything after an animation has completed.Anyways, calling
.fadeOut(0)
would fade out that element with no animation at all, just like instant. First parameter is the duration.http://api.jquery.com/fadeOut/
为什么不在添加类时隐藏它,因为 fadeOut(0) 没有动画,
当您需要在动画完成后完成某些操作时,您应该使用回调
$(...).fadeIn(400,function (){alert('这是回调'); }
,如果您不使用回调,则代码会在动画运行时运行,我不知道它是否有用,但有一个伪类
>:hover
在 css 中,请参见此处所以有了这个你可以做各种各样的事情,比如:
只要稍微玩一下,你就可以用 css 做很多事情
Why don't you just hide it while adding the class since fadeOut(0) doesnt have an animation
when you need something done after an animation has completed you should use callback
$(...).fadeIn(400,function(){ alert('this is the callback'); }
, if you dont use the callback the code is runned while the animation is going.and i dont know if its usefull but there is a pseudo class
:hover
in css, see hereso with this you can do various things like:
just play with it a little and you can do a lot with just css