当网址与#
匹配时,我修改了标准的Boostrap 3 Carousel,以便能够跳转到特定的幻灯片。它有效,但跳转到特定幻灯片时我的pager-text
没有更新。更新pager-text
的功能仅在项目滑动后才起作用。有人有解决方案吗?
我的HTML:
<li class="pager-text">1/{{ object.photo_set.count }}</li>
我的.js:
$(document).ready(function() {
//Initiate carousel
$('.carousel').carousel({
interval: false
})
$('.carousel').on('slid.bs.carousel', function () {
var carouselData = $(this).data('bs.carousel');
var currentIndex = carouselData.getActiveIndex();
var total = carouselData.$items.length;
// Display the current number of the slide
var text = (currentIndex + 1) + "/" + total;
$('.pager-text').text(text);
// Update location based on slide (index is 0-based)
window.location.hash = "#"+ parseInt($('.carousel .carousel-inner .item.active').index()+1);
});
});
var url = document.location.toString();
if (url.match('#')) {
// Clear active item
$('.carousel .carousel-inner .item.active').removeClass('active');
// Activate item number #hash
$('.carousel-inner div:nth-child(' + url.split('#')[1] + ')').addClass('active');
}
答案 0 :(得分:1)
通过更新if (url.match('#')) {
功能中的寻呼机文本来解决此问题。现在我可以输入www.mydomain.com/gallery-url/#4并将其发送到第四张图像,并且寻呼机文本显示4/total
。
$(document).ready(function() {
var url = document.location.toString();
var totalItems = $('.item').length;
//Initiate carousel
$('.carousel').carousel({
interval: false
})
$('.carousel').on('slid.bs.carousel', function () {
var currentIndex = $('div.active').index() + 1;
//Update pager-text
$('.pager-text').text(''+currentIndex+'/'+totalItems+'');
// Update location based on slide (index is 0-based)
window.location.hash = "#"+ parseInt($('.carousel .carousel-inner .item.active').index()+1);
});
if (url.match('#')) {
// Clear active item
$('.carousel .carousel-inner .item.active').removeClass('active');
// Activate item number #hash
$('.carousel-inner div:nth-child(' + url.split('#')[1] + ')').addClass('active');
//Update pager-text
$('.pager-text').text(''+url.split('#')[1]+'/'+totalItems+'');
}
});
答案 1 :(得分:0)
使用$('.carousel').carousel(number)
跳转到特定幻灯片。
来自bootstrap docs
.carousel(数)
将轮播循环到特定帧(基于0,类似于数组)。
有关使用哈希值跳转到特定幻灯片的更多信息,请参阅this question。
此外,跳转到幻灯片的代码将在注册更新pager-text
的自定义代码之前执行,它也不会注册为“幻灯片”,因为您没有使用内置函数跳转到滑动。
这样的事情可以为您提供所需的结果。
$(document).ready(function() {
//Initiate carousel
$('.carousel').carousel({
interval: false
})
//Event: Update pager-text on slide
$('.carousel').on('slid.bs.carousel', function () {
...
});
//Jump to slide on page load
$('.carousel').carousel(number);
});