jquery add a fade to an .addClass

こ雲淡風輕ζ 提交于 2019-12-01 02:25:37

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);  
});

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.

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

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