开发者

Incorporating Fade into addClass jQuery

I have this simple code:

$('.featureItems li').hover(
       function(){ $(this).addClass('hover') },
       function(){ $(this).removeClass('hover') }
)

How can i incorporate a fade effect, so th开发者_高级运维e add/remove class is a little more gradual?

Would i require animate()?

Thanks


If you're also using jQuery UI, it improves the CSS add/remove methods so that they accept a second parameter that's a delay (in milliseconds) to animate the CSS change over. To animate the change over a half-second, for example:

$('.featureItems li').hover(
   function(){ $(this).addClass('hover', 500) },
   function(){ $(this).removeClass('hover', 500) }
)

Update:

To prevent the animation queue from getting jammed up or inconsistent during quick hover in/out sequences, you can also force existing animations to stop before starting the add/removeClass:

$('.featureItems li').hover(
   function(){ $(this).stop(true).addClass('hover', 500) },
   function(){ $(this).stop(true).removeClass('hover', 500) }
)


Further to @Dave Ward's answer, there's a standalone plugin which does this in case you don't want to use jQuery UI.


In addition to @Dave Ward's answer, I had to remove the stop(true) part for the removeClass(), otherwise after the first mouseover/mouseout the mouseover part stops working:

$('.featureItems li').hover(
   function(){ $(this).stop(true).addClass('hover', 500) },
   function(){ $(this).removeClass('hover', 500) }
)


Another, non-javascript, alternative to this would be to change: .featureItems li in your CSS to have the following properties:

.featureItems li {
    transition: transform 1s, background-color 1s;
    -moz-transition: -moz-transform 1s, background-color 1s;
    -webkit-transition: -webkit-transform 1s, background-color 1s;
    -o-transition: -o-transform 1s, background-color 1s;
}

Which would then let CSS3 navigate between whatever changes you make in .hover, for example:

.hover {
    background-color: #DDD;
    transform:scale(1.1,1.1);
    -moz-transform:scale(1.1,1.1);
    -webkit-transform:scale(1.1,1.1);
    -o-transform:scale(1.1,1.1);
}

You can find more info about CSS3 Transitions here:

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜