Adding smooth fade/transition to jQuery hover function
I've got a functional hover replace that inserts a background image on hover and removes it on mouseout.
<script type='text/javascript'>
$(document).ready(function(){
$("#l-1").hover(function() {
$("#r-box").css("background","url('<?php bloginfo('template_directory'); ?>/i开发者_如何学Gomages/up.png') no-repeat transparent");
}, function() {
$("#r-box").css("background","#3DA7BC");
});
});
</script>
But I'm trying to get the transition to be smooth and graceful, not just in/out. I tried a variety of .animate functions to get it to work to no avail.
Thanks for any help!
You can try out animating the opacity of the object in question using jQuery.
My algorithm goes something like this:
1) animate the opacity to some value which makes it more transparent
2) in the callback section, change the background image using css({key:value})
3) animate the opacity back to the original value
$('.your-base-object').hover(function(){
$(this).animate({opacity: '0.9'}, 300, function(){
$(this).css({
background: "url('path/to/your-image')"
});
$(this).animate({
opacity: "1.0"
}, 300);
})
}, function(){
$(this).animate({opacity: '0.9'}, 300, function(){
$(this).css({
background: "url('path/to/your-image')"
});
$(this).animate({
opacity: "1.0"
}, 300);
})
});
You'll likely not be able to animate the background of an item like that. From jQuery's animate page:
All animated properties should be animated to a single numeric value, except as noted below; most properties that are non-numeric cannot be animated using basic jQuery functionality. (For example, width, height, or left can be animated but background-color cannot be.) Property values are treated as a number of pixels unless otherwise specified. The units em and % can be specified where applicable.
What I'd recommend doing is using some other way to display whatever's in the background image. Perhaps put it in a hidden span tag and animate it by doing a fadeIn or a fadeOut.
精彩评论