Update the current number of slide when jumping to specific item - Bootstrap 3 Carousel

前端 未结 2 605
被撕碎了的回忆
被撕碎了的回忆 2020-12-22 08:16

I modified the standard Boostrap 3 Carousel to be able to jump to a specific slide, when the url matches #. It works, but my pager-text is not upda

2条回答
  •  醉酒成梦
    2020-12-22 09:03

    Fixed it by updating the pager-text in the if (url.match('#')) { function. Now I can type www.mydomain.com/gallery-url/#4 and I'm sent to the fourth image, and the pager-text displays 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+'');
    
        }
    
    
    }); 
    

提交回复
热议问题