Bootstrap carousel - link to specific slide

2019-01-15 17:07发布

问题:

I have found a lot of help on displaying the current slide number in the html and linking to a particular slide on the current page but my question is a little different...

I need to be able to link to a particular slide in the carousel in another page. So I will have something like: a href="page2.html#slide2" on 'index.html'

When the user clicks this link, it takes them to the 'page2.html' page and with the second slide displayed.

Any help is appreciated. Thanks, Alex

回答1:

You can use a query string like... www.example.com?slide=2

$(document).ready(function(){

    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
            results = regex.exec(location.search);
        return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    $('#myCarousel').carousel(getParameterByName('slide'));
});

Or hash values like... www.example.com#2

$(document).ready(function(){
    $('#myCarousel').carousel(window.location.hash.substring(1));
});

Which ever you use, you have to only extract an integer from the url, so you may want to make the code a little more robust to ensure you are only moving the carousel if you get a valid integer and also check that it is within the bounds of the number of slides that exist within the carousel.

.carousel(number)

Cycles the carousel to a particular frame (0 based, similar to an array).



回答2:

New and improved version tests for a valid integer and defaults to 0:

function qs(key) {
    key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
    var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
    var slide = match && decodeURIComponent(match[1].replace(/\+/g, " "));
    if (Math.floor(slide) == slide && $.isNumeric(slide))
        return parseInt(slide);
    else
        return 0;
}
$('#myCarousel').carousel(qs('slide'));

Credits go to this and this question.