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

And*_*mes 9 jquery owl-carousel-2

我有以下代码块.我要做的就是在幻灯片放映中获取当前图像的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>
Run Code Online (Sandbox Code Playgroud)

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

wil*_*ies 22

您的代码无法正常工作的原因是没有为Owl Carousel定义的onChange回调.

有关可用选项,请参阅标题回调下的http://owlgraphic.com/owlcarousel/#customizing.

如果您更新它以使用"afterMove",它将在幻灯片移动后正常工作.

您可能还想考虑使用"afterAction",它会在启动时启动,移动和更新,具体取决于您的要求.

JS
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);
    }
});
Run Code Online (Sandbox Code Playgroud)

编辑

在进一步阅读评论中提供的链接和owl carousel 2的文档之后,这是一个使用owl carousel 2的工作示例.请参阅此jsfiddle

像测试中的任何东西一样,github问题和答案可能会很快过时.从这里的owl carousel 2网站上的文档中找到了解决方案

HTML
<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>
Run Code Online (Sandbox Code Playgroud) 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);
});
Run Code Online (Sandbox Code Playgroud)