fade in/out hover by jQuery

安稳与你 提交于 2019-12-02 10:49:47

问题


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


回答1:


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




回答2:


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/




回答3:


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



来源:https://stackoverflow.com/questions/3343326/fade-in-out-hover-by-jquery

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