简体   繁体   中英

Fading from one class to another with a spritesheet using Javascript/jQuery

I have a spritesheet with plenty of images which I switch to depending on the character's feelings. I've mapped out all of his expressions into classes.

.normal{
    background: url(background.png) 0 0;
}

.happy{
    background: url(background.png) 100% 0;
}

Depending on the circumstances, I remove the class from the div then give it the new class, such as this:

$('#div1').removeClass();
$('#div1').addClass(happy);

I'd like to make the transition between these smoother by fading from one image to the other. I've searched around and most examples I've found mentioned either a :hover css, but I want to be able to control it via Javascript code and not on a mouseover. There was also one solution I found that was to use transition: background 0.5s ease-in-out; , but this solution only moves the spritesheet from the first section to the other. Others suggested $('#div1').removeClass(currExpression).addClass(expression).fadeIn(500); , but it doesn't make a difference.

I also decided to do the transitioning with a good old

$('#div1').fadeOut();
$('#div1').removeClass();
$('#div1').addClass(expression);
$('#div1').fadeIn();

But it doesn't quite do what I want, as it fades away and fades in instead of fading from one class to another directly.

What I'd really like is to do as if the first section of my sprite sheet would fade into the second section of the sprite sheet as if they were two separate images, a bit like this: http://tinypic.com/view.php?pic=jv6wet&s=9#.VwCUO6QrK5g . Is there a possible way to do this in jQuery, CSS or Javascript?

this can be done with css... you forgot to add the transition timing function property and that might be what is going on. Try

transition: background 0.5s ease;

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