Hover img fadeIn next or fadeIn first img
I have simplified what I am trying to achieve from my previous question.
This is a example of the script I am trying to write: example when you hover over the image you can see the problem. Possible fix with a delay?
I have a list of product each with 2-5 thumbnail images. I want to create a hover function that cycles through the images hiding/showing the next image.
I did try to stack the images using z-index although this was causing too much of a problem.
This is the hove开发者_如何学JAVAr function that I have put together so far:
$(".image_cycle img").live("hover", function(){
if ($(this).next("img").is(":hidden")) {
$(this).next("img").fadeIn("slow",function(){
$(this).siblings("img").hide();
});
} else {
$(this).parent().find("img:first").fadeIn("slow",function(){
$(this).siblings().hide();
});
}
});
This is a lightweight version of a cycle plugin which I've just whipped up:
jQuery.fn.HoverCycle = function(params){
var defaults = {
"Timeout": 1500,
"FadeSpeed": "slow"
};
var opts = $.extend(defaults, params);
if(isNaN(opts.Timeout)){
throw "Hover Timeout value must be numeric";
}
(function(){
var valid = true;
if(isNaN(opts.FadeSpeed)){
opts.FadeSpeed = opts.FadeSpeed.toLowerCase();
valid = (opts.FadeSpeed == "slow" || opts.FadeSpeed == "fast");
}else if(opts.FadeSpeed <= 0){
valid = false;
}
if(!valid){
throw "FadeSpeed must be either numeric and above zero, or either 'slow' or 'fast'";
}
})();
return this.each(function (){
var cycleTimer;
var $firstImg = $currentImg = $(this).find("img:first");
$(this).mouseenter(function(){
cycleTimer = setInterval(function(){
var $nextImg = $currentImg.next();
if($nextImg.length == 0){
$nextImg = $firstImg;
}
$currentImg.fadeOut(opts.FadeSpeed, function(){
$nextImg.fadeIn(opts.FadeSpeed, function(){
$currentImg = $nextImg;
});
});
}, opts.Timeout);
}).mouseleave(function(){
clearInterval(cycleTimer);
});
});
};
Apply it to the container of the images, so in this case, the tag:
$(".image_cycle").HoverCycle();
It'll loop through the images in the order they're declared in the tag. You can override the fade speed and timeout duration via the constructor:
$(".image_cycle").Cycle({ "Timeout": 3000, "FadeSpeed": "fast" });
Where "Timeout" is the value in ms between it switching images, and "FadeSpeed" is the same permitted values as jquery's fade functions (ie "fast","slow", or a numeric value).
You could better use the jquery cycle plugin.
http://jquery.malsup.com/cycle/begin.html
Hope this helps.
http://jsfiddle.net/MtpPN/1/
here's an example, don't know exactly if that is what you want, but if it is a plugin would be overkill.
精彩评论