Automatic tab switch in javascript or jquery

2019-05-12 09:32发布

问题:

I built a featured tabbing system (4 tabs) with jquery. It works manually but I want to make it loop automatically, i.g. every 5 seconds. I can trigger each tab with the click even but I don't know how to go back to the beginning from 1st tab once it reach the last tab.

The coding too long to past here, so I have made a jsfiddle link to it: http://jsfiddle.net/ZSPX3/

I just wanna iterate through each tab and click them each, then start from the beginning of the tab again, as in I want an infinite slideshow. But I'm stuck...

I don't want any plugins, I wanna learn how to do this with my own hand, please.

Many thanks

回答1:

The key part here is to check the index of the currently-on tab and see if there's any tabs beyond it. If not, revert to the first tab. So:

HTML

<ul id='tabs'>
    <li class='on'>tab 1</li>
    <li>tab 2</li>
    <li>tab 3</li>
    <li>tab 4</li>
    <li>tab 5</li>
</ul>

CSS

#tabs { list-style: none; margin: 0; padding: 0; }
#tabs li { float: left; background: #ddd; padding: 6px; }
#tabs li.on { background: #f90; color: #fff; }

JS (jQuery assumed)

$(function() {

    //cache a reference to the tabs
    var tabs = $('#tabs li');

    //on click to tab, turn it on, and turn previously-on tab off
    tabs.click(function() { $(this).addClass('on').siblings('.on').removeClass('on'); });

    //auto-rotate every 5 seconds
    setInterval(function() {

            //get currently-on tab
        var onTab = tabs.filter('.on');

            //click either next tab, if exists, else first one
        var nextTab = onTab.index() < tabs.length-1 ? onTab.next() : tabs.first();
        nextTab.click();
    }, 5000);
});

We compare the (zero-indexed) index of the currently-on tab with the total number of tabs (-1, to account for the zero-indexing). If the former is lower than the latter, there's still some tabs to go; if not, i.e. they're equal, we've reached the end - go back to the start.

Hope this helps.



回答2:

Here's some code you can use:

jQuery:

setInterval(function() {
    var current = parseInt($('li.selected a').data('links-to').split('_')[1],10);
    var idx=current-1;
    var max = $('.carouselLinks li a').length;
    idx = (current<max) ? (idx+1):0;
    $('a:eq('+idx+')').trigger('click');
}, 3000);

Updated jsFiddle example.