简体   繁体   中英

fade css background images on hover

$(function(){
    $('#product .btn-purchase')
            .mouseover(function(){
                $(this).stop().animate($(this).addClass('.btn-purchase-hover'), {duration:500})
            })
            .mouseout(function(){
                $(this).stop().animate($(this).removeClass('.btn-purchase-hover'), {duration:500})
    });
});

.. not sure why this isn't work, what am I doing wrong?

The animate function predominately works on a numeric CSS property.

for details you can look here : http://api.jquery.com/animate/

EDIT: I would suggest that you use the fadeIn / out method in jQuery instead. For instance , you could do something like this below. ( Code off the top of my head, assumes you have the div with the correct image after the .btn-purchase )

$(function(){
    $('#product .btn-purchase')
            .mouseover(function(){
                var $this = $(this);
                  $this.fadeOut(function(){ $this.next().fadeIn(); });
            })
            .mouseout(function(){
                  $this.fadeOut(function(){ $this.prev().fadeIn(); });
    });
});

I would also like to add that incase you are not supporting IE, then using CSS transitions may be of help.

Have a look at this answer animating addClass/removeClass with jquery since it is definately a better / more efficient method in my opinion

Shreyas N

You need to use document.ready so your code runs after the DOM has completely loaded, something like this :

$(document).ready(function() {
    $('#product .btn-purchase')
            .mouseover(function(){
                $(this).stop().animate($(this).addClass('.btn-purchase-hover'), {duration:500})
            })
            .mouseout(function(){
                $(this).stop().animate($(this).removeClass('.btn-purchase-hover'), {duration:500})
    });
});

JQuery animate is used to animate CSS properties and not classes. As this answer shows, a better way might be to use CSS transitions (if you're only supporting CSS3). Alternatively, if you want to animate lots of things you'll need to supply them as CSS properties in the .animation() method.

Hope that solves you're issue.

I know, that this is not exactly an answer to your question. But as Jan commented before, you might think about implementing this in css.

Just to give you an idea what it might look like:

 #product .btn-purchase{
     background-color: blue;
     transition: all 1s ease-in;
     -webkit-transition: all 1s ease-in;
     -moz-transition: all 1s ease-in;
 }


 #product .btn-purchase:hover{
     background-color:  red;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM