jQuery cycle plugin customizing
I'm using the jQuery Cycle plugin to start a slidshow of images when hovering over the initial image. This works fine. What I want after that is to have the slideshow stop when hovered off, and have a manual slideshow (next/prev buttons) start. This currently works, but the slideshow starts from the beginning each time it's initialized. I want it to begin at the current image that's loaded.
I was playing around with getting the image's index from the DOM (as it's the only one wi开发者_开发百科th display:block) and using the option 'startingSlide' to resume it, but my index keeps returning as -1.
jQuery('#home-menu li').hover(function()
{
setImages(jQuery(this).attr('title'), jQuery(this).find('.subtitle').text());
jQuery('#main .blog #projects .gallery .slideshow').cycle(
{
fx: 'scrollHorz',
easing: 'easeOutBounce',
speed: 2000,
delay: 0
});
}, function()
{
// Before loading the images for the clickable slideshow, find the current image in the DOM array to use as the starting position
slideshowStart = jQuery('.gallery .slideshow img:visible').index(this);
console.log('Index: ' + slideshowStart);
setImages(jQuery(this).attr('title'), jQuery(this).find('.subtitle').text());
jQuery('#main .blog #projects .gallery .slideshow').cycle('stop').cycle(
{
fx: 'scrollHorz',
easing: 'easeOutBounce',
startingSlide: slideshowStart,
speed: 2000,
timeout: 0,
next: "#main .blog #projects .gallery span.span2",
prev: "#main .blog #projects .gallery span.span1"
});
});
setImages() just loads images into the DOM based on what li is being hovered over. Nothing special there.
I want the image to be resumed when hovered over and hovered off. I've left out the resume part for hover on for the moment while I was trying to get it working - In case you were wondering.
The problem is in the hover out callback:
slideshowStart = jQuery('.gallery .slideshow img:visible').index(this);
1) First, the jQuery statement selects all elements that match the selector. The cycle plugin ensures that only one image inside its container is displayed, so this satement selects a maximum of one img
element.
2) Second, the index
function searches the elements selected in step 1 (the single img
element) to see if it can find one that matches the subject (the argument provided to the index function). In your case, the subject is this
, which in the context of the hover callback is jQuery(#home-menu li)
.
li
elements never match img
elements, so this call to index()
will always return -1 (for 'no object found').
To fix this, modify the statement like so:
slideshowStart = $('.slideshow img').index($('img:visible'));
1) First, this selects all the img
elements in your <div class='slideshow'>
element.
2) Second, it returns the index of the first visible img
element in that list.
If you simply want it to pause and play, use the options:
jQuery('#home-menu li').hover(function() { $("#yourSlideshow").cycle("resume"); }, function { $("#yourSlideshow").cycle("pause"); });
精彩评论