我目前正在使用 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 代码。我有十四张图片,所以我的代码循环遍历所有十四张图片并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 将相应地更新其锚点。为什么?因为如果我的用户单击图像(其中包含 a 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 上进行搜索,看看是否可以做到这一点,但是,没有运气。
我还检查了这个线程:append /remove anchor name from current url without refresh