fade in/out hover by jQuery

左心房为你撑大大i 提交于 2019-12-02 04:30:13

These two functions are opposites of each other, so should work... (code updated)

$('#header #menu li a').hover(function () {
  $(this).fadeOut(0).addClass('hover').fadeIn(300);
},
function () {
  $(this).fadeOut(300)
         .queue(function(){ $(this).removeClass('hover').fadeIn(0).dequeue() });
});

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...)

Like answered many times here on SO, you need to use the callbacks from jQuery fx methods to do anything after an animation has completed.

$('#menu li a').hover(function(){
    $(this).fadeOut('fast', function(){
        $(this).addClass('hover').fadeIn(300);
    });
}, function(){
});

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/

Why don't you just hide it while adding the class since fadeOut(0) doesnt have an animation

$('#header #menu li a').hover(function () {
  $(this).hide().addClass('hover').fadeIn(300);
},
function () {
  $(this).hide().removeClass('hover').show();
  //  as there is no fading time the line above will be equal to
  $(this).removeClass('hover');
});

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 here

The :hover pseudo-class is supported in all major browsers.

so with this you can do various things like:

#header #menu li a:hover { ...set style of 'a' when over 'a' }
#header #menu li:hover a { ...set style of 'a' when over 'li' }

just play with it a little and you can do a lot with just css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!