What is the best way to do a javascript faded image mouseover and mouseout effect?
I would imagine jQuery would be the library to use in order to do this. I can certainly figure out how to switch the source of an image 开发者_StackOverflowon mouseover and then switch it back on mouseout. But how could I achieve this effect with a fade to and from the images?
I have tried to achieve this already using the jQuery Cycle plugin and I was unsuccessful. I feel maybe there's an easier way to do this. I'd appreciate the help, any thoughts?
Put an image in a DIV and set the background of the DIV to the first image. Put an image tag in the DIV and point the SRC to the second image.
Now you can fiddle with the opacity of the IMG, exposing the background image behind it without having to swap anything.
use .opacity()
Make sure you put dimensions on the wrapper DIV or else it will vanish once the opacity of the image inside gets to zero.
<div class="wrapper">
<img src="..." />
</div>
CSS3 is adding a bunch of transition properties to handle things like this, but for the moment if you're set on using jQuery you could make use of the .animate
function combined with mouseenter
and mouseleave
.
Example:
$('img')
.mouseenter(function() {
$(this).stop(true,true).animate({ opacity: 0.5 }, 2000);
});
.mouseleave(function() {
$(this).stop(true,true).animate({ opacity: 1 }, 2000);
});
The .stop
will clear the previous animation and make it finish so that if the user were to hover quickly over the element several times, it won't let the animations build up in a long queue.
You can try this
$(function(){
$("imageSelector).mouseover(function(){
$(this).data("oldSrc", this.src).attr("src", "newSource").stop().fadeT0(500, 1);
}).mouseout(function(){
$(this).attr("src", $(this).data("oldSrc")).stop().fadeTo(500, 0.5);
});
});
精彩评论