猫头鹰轮播2 在拖动时更新 URL 哈希导航


OwlCarousel2 Updating URL Hash Navigation on Drag

我目前正在使用 OwlCarousel2 来满足我的轮播需求。我选择了OwlCarousel2而不是OwlCarousel1,因为它有一个URL哈希导航:http://www.owlcarousel.owlgraphic.com/demos/urlhashnav.html

<div id="contestant-carousel">
    <div id="poll-images" class="owl-carousel">
        <?php
            for($counter = 1; $counter <= 14; $counter++) {
                echo "<div class='item' data-hash='$counter'><a href='" . HTTP_SERVER . "vote.php?contestant_id=$counter'><img src='/images/contestants_mobile/$counter.png' alt='$counter'></a></div>";
            }
        ?>
    </div>
</div>

以上是我用来生成轮播的 PHP 代码。我有 14 张图像,所以我的代码遍历所有 14 张图像,并为每个图像添加一个data-hash对象(用于锚点导航需求)。

以下是我的Javascript代码:

$(document).ready(function() {
    $("#poll-images").owlCarousel({
        items: 1,
        loop:false,
        center:true,
        margin:10,
        lazyLoad:false,
        URLhashListener:true,
        onDragged:callback,
        autoplayHoverPause:true,
        startPosition: 'URLHash'
    });
    function callback(event) {
        window.location.hash = event.item.index;
        console.log(event.item.index);
    }
});

现在,如果用户在其URL中手动添加哈希值,则上述轮播可以完美运行,即 someurl.com/voting.php#4,这将导航到第四个图像。

但是,我想做的是,如果 url 导航到 someurl.com/voting.php ,当他们滚动浏览每个图像时,我的 URL 会相应地更新其锚点。为什么?因为如果我的用户单击图像(其中包含一个href),并且他们转到上一页,他们可以导航回他们正在查看的图像,而不是转到第一个图像的默认行为。

根据 OwlCarousel2

API(实际上与 OwlCarousel1 有很大不同),要获取当前项目,您可以执行以下操作:

function callback(event) {
    // Provided by the core
    var element   = event.target;         // DOM element, in this example .owl-carousel
    var name      = event.type;           // Name of the event, in this example dragged
    var namespace = event.namespace;      // Namespace of the event, in this example owl.carousel
    var items     = event.item.count;     // Number of items
    var item      = event.item.index;     // Position of the current item
    // Provided by the navigation plugin
    var pages     = event.page.count;     // Number of pages
    var page      = event.page.index;     // Position of the current page
    var size      = event.page.size;      // Number of items per page }

具体来说,使用 event.item.index .我的代码正是这样做的!但是我无法检索当前索引!我的错误是:Uncaught TypeError: Cannot read property 'item' of undefined在Chrome的控制台下。

JS大师的任何帮助将不胜感激!

我尝试在StackOverflow以及OwlCarousel2 API上搜索,看看我是否可以做到这一点,但是没有运气。

我还检查了这个线程:从当前 url 附加/删除锚点名称而不刷新

在这里找到了修复程序!

    // jQuery method on
    owl.on('changed.owl.carousel', function(property){
        var current = property.item.index;
        window.location.hash = current + 1;
    });

猫头鹰旋转木马2家伙需要更新他的API =/

在这里找到: 猫头鹰旋转木马 2 - 获取当前幻灯片的 src