如何获得下一张图片的src to dinade Nivo Slider

时间:2012-07-07 17:28:24

标签: jquery nivo-slider

我希望能够获得下一张图片的src。所以我在想像

这样的东西
 $('#nivo_slider').nivoSlider({

      beforeChange: function(){

           //get src of next image
    }
};

我可以通过执行以下操作获取当前图像源:

var currentImageSrc=$('#nivo_slider').data("nivo:vars").currentImage.attr('src');       
var index=currentImageSrc.lastIndexOf("/")+1;        
var imageName= currentImageSrc.substr(index);

但我不确定如何让下一个加载

我的HTML如下:

<div id="nivo_slider>
   <img src="img1" />
   <img src="img2" />
   <img src="img3" />
   <img src="img4" />

</div>

1 个答案:

答案 0 :(得分:4)

嗯,这是一种方法(尽管花了一些时间尝试,似乎没有一种明显更容易的方式):

/* Nivo seems to add images in order to implement its effects,
   so we need to grab a reference to the original images, or, at least, their `src` */

var images = $('#slider img').map(
    function() {
        return $(this).attr('src');
    });

$('#slider').nivoSlider({
    beforeChange: function() {
        var wrap = $('#slider'),
            // caching data because I'm accessing it twice:
            data = wrap.data('nivo:vars'),
            // the current src:
            current = data.currentImage.attr('src'),
            len = data.totalSlides,
            /* compares the current src against the srcs stored in the
               images variable, and returns the index at which it was
               found */
            arrayPos = $.inArray(current, images),
            nextSrc;

        if (arrayPos == (len - 1)) {
            /* if the array position of the src is equal to length-1
               (zero-based arrays in JS), then the next image to be
               shown will be the first in the array */
            nextSrc = images[0];
        }
        else {
            // otherwise get the next src from the next position in the array
            nextSrc = images[arrayPos + 1];
        }

        $('#output code.src').text(nextSrc);
    }
});​

JS Fiddle demo

参考文献: