简体   繁体   English

javascript或jquery中的自动制表符切换

[英]Automatic tab switch in javascript or jquery

I built a featured tabbing system (4 tabs) with jquery. 我用jquery构建了一个特色标签系统(4个标签)。 It works manually but I want to make it loop automatically, ig every 5 seconds. 它手动工作,但我想让它自动循环,每隔5秒ig。 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/ 编码太久了,不能过去,所以我做了一个jsfiddle链接: 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 非常感谢

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 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 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) JS(jQuery假设)

$(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). 我们将当前选项卡的(零索引)索引与选项卡的总数进行比较(-1,以考虑零索引)。 If the former is lower than the latter, there's still some tabs to go; 如果前者低于后者,那么还有一些标签要去; if not, ie they're equal, we've reached the end - go back to the start. 如果没有,即他们是平等的,我们已经到了最后 - 回到起点。

Hope this helps. 希望这可以帮助。

Here's some code you can use: 以下是您可以使用的一些代码:

jQuery: 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 . 更新了jsFiddle示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM