jquery add a fade to an .addClass

2019-02-16 09:28发布

问题:

How do I fade .addClass in and out.

Here is the link -

http://www.bikramyogajoondalup.com.au/about-bikram-yoga/postures-benefits.html

and here is the code -

$(document).ready(function() {
  $('#menu li#Q_01,#menu li#Q_03,#menu li#Q_05,#menu li#Q_07,#menu li#Q_09,#menu li#Q_11,#menu li#Q_13').hover(function() {
    $(this).addClass('pretty-hover');
  }, function() {
    $(this).removeClass('pretty-hover');
  });
});

$(document).ready(function() {
  $('#menu li#Q_02,#menu li#Q_04,#menu li#Q_06,#menu li#Q_08,#menu li#Q_10,#menu li#Q_12').hover(function() {
    $(this).addClass('pretty-hover_01');
  }, function() {
    $(this).removeClass('pretty-hover_01');
  });
});

Thanks

回答1:

If jQuery UI is an option, you can use .toggleClass(class, duration) for this.

Also, you can probably simplify your selector, it looks like :even and :odd will do the job based on your current selector, like this:

$(function() {
  $('#menu li:even').hover(function() {
    $(this).toggleClass('pretty-hover', 500);
  });
  $('#menu li:odd').hover(function() {
    $(this).toggleClass('pretty-hover_01', 500);
  });
});

I realize the above seems backwards, but :even does select the first element, because it's 0 based, so even selects 0th, 2nd, 4th, etc. I hope you'll agree, makes it a bit easier to maintain :)

Edit based on comments - Since .toggleclass() sticks on quick hovers, here's an alternative that works as expected, just a bit longer:

$('#menu li.post:even').hover(function() {
  $(this).stop().animate({ backgroundColor: '#009FDD', color: '#FFF' }, 500);
}, function() {
  $(this).stop().animate({ backgroundColor: '#FFFFFF', color: '#666' }, 500);  
});
$('#menu li.post:odd').hover(function() {
  $(this).stop().animate({ backgroundColor: '#623A10', color: '#FFF' }, 500);
}, function() {
  $(this).stop().animate({ backgroundColor: '#FFFFFF', color: '#666' }, 500);  
});


回答2:

If you want to fade the colours of an element, you'll need to use jQuery UI which has more advanced support for fading and animating (the core jQuery can only fade/animate integer properties: colours don't work).

It even supports animating all the properties in an entire CSS class, so using jQuery UI, you should be able to achieve the effect you want.



回答3:

the jQuery .animate function is the best bet, although this won't let you animate between CSS classes - you have to specify the individual styles.

You would be better using the jQquery UI, as this would provide for this sort of functionality, as stated in the jQuery animate page:

The jQuery UI project extends the .animate() method by allowing some non-numeric styles such as colors to be animated. The project also includes mechanisms for specifying animations through CSS classes rather than individual attributes