Animate opacity on hover (jQuery)

2020-08-23 07:38发布

We have a link:

<a href="#">
    Some text
    <span style="width: 50px; height: 50px; background: url(image.png); overflow: hidden; opacity: 0;"></span>
</a>

And we want to change opacity of <span> with some animation, when the link is hovered.

How would we do it?

3条回答
兄弟一词,经得起流年.
2楼-- · 2020-08-23 08:03

Use .fadeTo():

$( 'a' ).hover(
    function() { $( this ).fadeTo( 'fast', '1'); },
    function() { $( this ).fadeTo( 'fast', '.4'); }
);

Demo: see fiddle

查看更多
贪生不怕死
3楼-- · 2020-08-23 08:07

Like this:

$('a:has(span)').hover(
    function() { $('span', this).fadeIn(); },
    function() { $('span', this).fadeOut(); }
);
查看更多
你好瞎i
4楼-- · 2020-08-23 08:10

Another possible solution:

$("a span").hover(function(){
    $(this).stop().animate({"opacity": 1});
},function(){
    $(this).stop().animate({"opacity": 0});
});

If you use fadeOut(), the span will collapse, this way it won't

EDIT

This is much better:

$('a:has(span)').hover(function() { 
    $('span', this).stop().animate({"opacity": 1}); 
},function() { 
    $('span', this).stop().animate({"opacity": 0}); 
});
查看更多
登录 后发表回答