Owl Carousel 2 - 获取当前幻灯片的src

12
我有以下的代码块。我想要做的只是获取幻灯片中当前图片的src。但它并没有起作用,尽管它能够正常地切换幻灯片,但在控制台中什么都没有显示。
HTML:
<div id="banner" class="owl-carousel">
    <img src="template/banner-1.jpg" alt="">
    <img src="template/banner-2.jpg" alt="">
    <img src="template/banner-1.jpg" alt="">
    <img src="template/banner-2.jpg" alt="">
</div>

jQuery:

var owl = $(".owl-carousel");
owl.owlCarousel({
    loop: true,
    autoplay: true,
    items: 1,
    animateOut: 'fadeOut',
    onChange: function (elem) {
      var current = this.currentItem;
      var src = elem.find(".owl-item").eq(current).find("img").attr('src');
      console.log('Image current is ' + src);
    }
});
1个回答

26
你的代码无法正常工作的原因是没有为 Owl Carousel 定义 onChange 回调函数。
请查看位于http://owlgraphic.com/owlcarousel/#customizing 的回调选项下方,了解可用选项。
如果你更新它以使用 "afterMove",则在幻灯片移动后它将正常工作。
你可能还想考虑使用“afterAction”,它可以根据你的需求在启动、移动和更新时触发。
var owl = $(".owl-carousel");
owl.owlCarousel({
    loop: true,
    autoplay: true,
    items: 1,
    animateOut: 'fadeOut',
    afterMove: function (elem) {
      var current = this.currentItem;
      var src = elem.find(".owl-item").eq(current).find("img").attr('src');
      console.log('Image current is ' + src);
    }
});

编辑

在阅读评论中提供的链接和owl carousel 2文档后,这里提供了一个使用owl carousel 2的工作示例。请查看此jsfiddle

像任何测试版一样,github问题和答案可能很快过时。从owl carousel 2网站的文档中找到了解决方案,在此处

<div id="banner" class="owl-carousel">
    <img src="http://www.live-on-the-edge.com/wp-content/uploads/2014/06/Sam-Tomkins-730x547.jpg" alt=""/>
    <img src="http://static.guim.co.uk/sys-images/Sport/Pix/pictures/2009/6/11/1244720277422/Aussie-Rugby-League-001.jpg" alt=""/>
    <img src="http://static.guim.co.uk/sys-images/Sport/Pix/pictures/2010/1/7/1262873655905/Rugby-referee-001.jpg" alt=""/>
    <img src="http://static.guim.co.uk/sys-images/Sport/Pix/columnists/2011/3/3/1299187263691/football-league-premier-l-007.jpg" alt=""/>
</div>
JS
var owl = $(".owl-carousel");
owl.owlCarousel({
    loop: true,
    autoplay: true,
    items: 1,
    animateOut: 'fadeOut'
});

// jQuery method on
owl.on('changed.owl.carousel',function(property){
    var current = property.item.index;
    var src = $(property.target).find(".owl-item").eq(current).find("img").attr('src');
    console.log('Image current is ' + src);
});

实际上,onChange是有效的(https://github.com/OwlFonk/OwlCarousel/issues/222#issuecomment-41021575),没有函数会有问题,我想。如果我在onChange中运行警报或console.log,它就可以正常工作。我正在使用猫头鹰走廊2。afterMove在我的原始代码块中使用,但也不起作用,onChange是我需要的脚本。 - Andy Holmes
@AndyHolmes - 刚刚查看了 Owl Carousel 2 网站上的文档,并已经为您使其正常工作。请参见上面编辑过的答案。 - wildavies
1
非常感谢!这解决了我的问题。所以这就是通过你的方法获取item.index的方式。谢谢! - theGreenCabbage
1
Owl Carousel 2 中没有 afterActionafterMove。您应该将其删除作为最佳答案,以免像我这样的落后者感到困惑... - user4325086
@LyndonJohnson - 请阅读整个问题,包括编辑部分,以获得正确的答案。 - wildavies

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接