javascript或jquery中的自动选项卡切换 [英] Automatic tab switch in javascript or jquery

查看:74
本文介绍了javascript或jquery中的自动选项卡切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用jquery构建了一个功能强大的制表系统(4个制表符).它手动工作,但我想使其自动循环,例如每5秒.我什至可以点击来触发每个选项卡,但是我不知道一旦到达最后一个选项卡,如何从第一个选项卡回到起始位置.

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.

这里的编码太久了,所以我已经建立了一个jsfiddle链接: http://jsfiddle.net/ZSPX3/

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.

非常感谢

推荐答案

此处的关键部分是检查当前打开的选项卡的索引,看是否还有其他选项卡.如果不是,请还原到第一个标签.所以:

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)

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);
});

我们将当前打开的选项卡的(零索引)索引与选项卡总数(-1,以说明零索引)进行比较.如果前者低于后者,那么还有一些选项卡可供选择.如果不是,即它们相等,那么我们就到了终点-回到起点.

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.

希望这会有所帮助.

这篇关于javascript或jquery中的自动选项卡切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆