Javascript 如何使用 jQuery 构建简单的选项卡?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11645081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:38:51  来源:igfitidea点击:

How to build simple tabs with jQuery?

javascriptjqueryhtmlcsstabs

提问by Ashley Briscoe

I have the following code: fiddle

我有以下代码:小提琴

Which works great in websites I create my self and with no JS the tabs act as jump links to the relevant sections. When placed in the bespoke CMS I am forced to use at the moment the jump links don't work. I have tried adding more relative links to the tabs which makes it work with no JS but with JS the tabbed content doesn't show.

这在我自己创建的网站中效果很好,没有 JS,选项卡充当到相关部分的跳转链接。当放置在定制的 CMS 中时,我现在被迫使用跳转链接不起作用。我尝试向选项卡添加更多相关链接,这使其在没有 JS 的情况下工作,但使用 JS 时,选项卡式内容不显示。

Am I missing something?

我错过了什么吗?

html:

html:

<ul id="tabs">

      <li><a href="#tab1">test1</a></li>
      <li><a href="#tab2">test2</a></li>
      <li><a href="#tab3">test3</a></li>
      <li><a href="#tab4">test4</a></li>

</ul>
      <div class="container" id="tab1">Some content</div>
      <div class="container" id="tab2">Some content</div>
      <div class="container" id="tab3">Some content</div>
      <div class="container" id="tab4">Some content</div>

jQuery:

jQuery:

$('#tabs li a:not(:first)').addClass('inactive');
$('.container').hide();
$('.container:first').show();
$('#tabs li a').click(function(){
    var t = $(this).attr('href');
    $('#tabs li a').addClass('inactive');        
    $(this).removeClass('inactive');
    $('.container').hide();
    $(t).fadeIn('slow');
    return false;
})

if($(this).hasClass('inactive')){ //this is the start of our condition 
    $('#tabs li a').addClass('inactive');         
    $(this).removeClass('inactive');
    $('.container').hide();
    $(t).fadeIn('slow');    
}

回答by Barlas Apaydin

I am guessing your website is having problems with href, i presume that when user clicks a href, website automatically eradicating itself.

我猜你的网站在使用 href 时有问题,我认为当用户点击一个 href 时,网站会自动根除自己。

Here is new solution's jsFiddle.

这是新解决方案的 jsFiddle。

I have a new solution for you:

我有一个新的解决方案给你:

updated jQuery:

更新的jQuery:

$('#tabs li a').click(function(){
  var t = $(this).attr('id');

  if($(this).hasClass('inactive')){ //this is the start of our condition 
    $('#tabs li a').addClass('inactive');           
    $(this).removeClass('inactive');

    $('.container').hide();
    $('#'+ t + 'C').fadeIn('slow');
 }
});


new html markup:

新的 html 标记:

<ul id="tabs">

      <li><a id="tab1">test1</a></li>
      <li><a id="tab2">test2</a></li>
      <li><a id="tab3">test3</a></li>
      <li><a id="tab4">test4</a></li>

</ul>
<div class="container" id="tab1C">1Some content</div>
<div class="container" id="tab2C">2Some content</div>
<div class="container" id="tab3C">3Some content</div>
<div class="container" id="tab4C">4Some content</div>

回答by user2185340

$(document).ready(function() {
$("#content div").hide(); // Initially hide all content
$("#tabs li:first").attr("id","current"); // Activate first tab
$("#content div:first").fadeIn(); // Show first tab content
$('#tabs li a').click(function(e) {
    e.preventDefault();
    if ($(this).attr("id") == "current"){ //detection for current tab
     return       
    }
    else{             
    $("#content div").hide(); //Hide all content
    $("#tabs li").attr("id",""); //Reset id's
    $(this).parent().attr("id","current"); // Activate this
    $( $(this).attr('href')).fadeIn(); // Show content for current tab
    }
});

});

});

See Demo: http://jsfiddle.net/pradeepk00786/5ezT3/

见演示:http: //jsfiddle.net/pradeepk00786/5ezT3/

回答by incorelabs

Solution JSFiddle::https://jsfiddle.net/incorelabs/mg6e4ren/74/

解决方案 JSFiddle:: https://jsfiddle.net/incorelabs/mg6e4ren/74/

Implementing Tabs is really simple, I have modified the HTML for your question a bit. Removed the anchor tags coz they are not needed.

实现 Tabs 非常简单,我已经针对您的问题稍微修改了 HTML。删除了锚标签,因为它们不需要。

HTML

HTML

<ul>
    <li class="tab-switcher" data-tab-index="0" tabindex="0">
        Tab 1
    </li>
    <li class="tab-switcher" data-tab-index="1" tabindex="0">
        Tab 2
    </li>
    <li class="tab-switcher" data-tab-index="2" tabindex="0">
        Tab 3
    </li>
    <li class="tab-switcher" data-tab-index="3" tabindex="0">
        Tab 4
    </li>
</ul>
<div id="allTabsContainer">
    <div class="tab-container" data-tab-index="0">
        Some content for Tab - 1
    </div>
    <div class="tab-container" data-tab-index="1" style="display:none;">
        Some content for Tab - 2
    </div>
    <div class="tab-container" data-tab-index="2" style="display:none;">
        Some content for Tab - 3
    </div>
    <div class="tab-container" data-tab-index="3" style="display:none;">
        Some content for Tab - 4
    </div>
</div>

HTML De-Mystified

HTML 解谜

  1. Add the "tab-switcher" class to each "li" element as well as tabindex="0" to make it accessible.
  2. Give a "data-tab-index" attribute to each "li".
  3. Add the "tab-container" class to each Tabbed Container. Also provide a "data-tab-index" attribute to each container which corresponds to the "data-tab-index" attribute on the "li" element.
  4. Show only the container you want visible, hide the others using "display:none".
  5. Provide a parent container for all the content of the tabbed containers. In this example this is the "allTabsContainer" div.
  1. 将“tab-switcher”类添加到每个“li”元素以及 tabindex="0" 以使其可访问。
  2. 给每个“li”一个“data-tab-index”属性。
  3. 将“tab-container”类添加到每个选项卡式容器。还为每个容器提供一个“data-tab-index”属性,该属性对应于“li”元素上的“data-tab-index”属性。
  4. 仅显示您希望可见的容器,使用“display:none”隐藏其他容器。
  5. 为标签式容器的所有内容提供一个父容器。在这个例子中,这是“allTabsContainer”div。

jQuery

jQuery

$(document).ready(function () {
    var previousActiveTabIndex = 0;

    $(".tab-switcher").on('click keypress', function (event) {
        // event.which === 13 means the "Enter" key is pressed

        if ((event.type === "keypress" && event.which === 13) || event.type === "click") {

            var tabClicked = $(this).data("tab-index");

            if(tabClicked != previousActiveTabIndex) {
                $("#allTabsContainer .tab-container").each(function () {
                    if($(this).data("tab-index") == tabClicked) {
                        $(".tab-container").hide();
                        $(this).show();
                        previousActiveTabIndex = $(this).data("tab-index");
                        return;
                    }
                });
            }
        }
    });
});

jQuery De-Mystified

jQuery 解谜

  1. The click and keypress listener on the "tab-switcher" gets initialized on "document.ready". (Note: The keypress only registers the "Enter" key)
  2. The variable "previousActiveTabIndex" keeps a track of the previous active tab so that if we press on the same tab again and again, it can be ignored.
  3. We run an EACH loop on the "tab-container". This is done to know which tab should be displayed. If the "data-tab-index" data attribute on each matches, we display that tab.
  4. We keep the value of the "data-tab-index" saved in "previousActiveTabIndex" which helps us keep a track of the previous tab which was clicked.
  1. “tab-switcher”上的点击和按键监听器在“document.ready”上初始化。(注意:按键仅注册“Enter”键)
  2. 变量“previousActiveTabIndex”跟踪前一个活动选项卡,因此如果我们一次又一次地按下同一个选项卡,它可以被忽略。
  3. 我们在“标签容器”上运行 EACH 循环。这样做是为了知道应该显示哪个选项卡。如果每个匹配的“data-tab-index”数据属性,我们将显示该选项卡。
  4. 我们将“data-tab-index”的值保存在“previousActiveTabIndex”中,这有助于我们跟踪点击的上一个选项卡。

If there are doubts or if someone has suggestions, do comment on the post.

如果有疑问或有人有建议,请在帖子中发表评论。

回答by Ilyas karim

Include jquery:

包括jQuery:

https://code.jquery.com/jquery-3.1.1.min.js

HTML:

HTML:

<br>
<div align="center" >
  <button data-toggle="tab" data-tabs=".gtabs.demo" data-tab=".tab-1" class="btn btn-info" >Tab 1</button>
  <button data-toggle="tab" data-tabs=".gtabs.demo" data-tab=".tab-2" class="btn btn-info" >Tab 2</button>
  <button data-toggle="tab" data-tabs=".gtabs.demo" data-tab=".tab-3" class="btn btn-info" >Tab 3</button>
</div>
<br />
<div class="gtabs demo" >
  <div class="gtab active tab-1">
    <h1>Gtab 1</h1>
  <button data-toggle="tab" data-tabs=".gtabs.demo" data-tab=".tab-2" class="ui button" >Tab 2</button>
  </div>

  <div class="gtab tab-2">
    <h1>Gtab 2</h1>
    <p>
      Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi minima fugit, est facere molestiae quod pariatur. Consectetur natus, blanditiis laborum possimus doloremque harum adipiscelit. Nisi minima fugit, est facere molestiae quod pariatur. Consectetur natus, blanditiis laborum possimus doloremque harum adipisci debitis similique, nostrum provident ut dolelit. Nisi minima fugit, est facere molestiae quod pariatur. Consectetur natus, blanditiis laborum possimus doloremque harum adipisci debitis similique, nostrum provident ut dolelit. Nisi minima fugit, est facere molestiae quod pariatur. Consectetur natus, blanditiis laborum possimus doloremque harum adipisci debitis similique, nostrum provident ut doli debitis similique, nostrum provident ut dolore.
    </p>
  </div>

  <div class="gtab tab-3">
    <h1>Gtab 3</h1>
  </div>
</div>
<p>
  Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nisi consequatur qui nostrum deleniti, quaerat. Voluptate quisquam nulla, sit error, quas mollitia sint veniam at rem corporis dolore, eaque sapiente qui.
</p>

CSS:

CSS:

.gtabs {
  position: relative;
  .gtab {
    background: #eee;
    position: absolute;
    width: 100%;
    opacity: 0;
    visibility: hidden;
    padding: 10px;
    top: 5px;
    transition: all 0.4s;
    &.active {
      opacity: 1;
      visibility: visible;
      top: 0;
      transition: all 0.4s;
    }
  }
}

JS:

JS:

$("[data-toggle='tab']").click(function () {
  var tabs = $(this).attr('data-tabs');
  var tab = $(this).attr("data-tab");
  $(tabs).find(".gtab").removeClass("active");
  $(tabs).find(tab).addClass("active");
});

Demo: http://codepen.io/iksdatoo/pen/NjOZrm

演示:http: //codepen.io/iksdatoo/pen/NjOZrm

回答by Sanket Patil

    <script>
 $('.tabheading li').click(function () {
        var tabid = $(this).attr("rel");
        $(this).parents('.tabcontainer').find('.active').removeClass('active');
        $('.tabbody').hide();
        $('#' + tabid).show();
        $(this).addClass('active');

        return false;
    });
</script>

Click here

点击这里

回答by Code Spy

Responsive Tabswith AutoPlay feature. These don't need any plugin

具有自动播放功能的响应式标签。这些不需要任何插件

Demo Link

演示链接

Source Link

来源链接

enter image description hereenter image description here

在此处输入图片说明在此处输入图片说明

HTML

HTML

    <div class="row responsive-tab-wrapper">
        <div class="col-md-3 tab-items-list">
            <ul class="resp-tabs-list">
                <li class="resp-tab-item">TAB 1</li>
                <li class="resp-tab-item">TAB 2</li>
                <li class="resp-tab-item">TAB 3</li>
            </ul>
        </div>
        <div class="col-md-9 resp-tabs-container">
            <div class="resp-tabs-container-item">
                <div class="prod-tab-content">
                    <h4>TAB 1 TITLE</h4>
                    <p>
                        TAB 1 CONTENT
                    </p>

                </div>
            </div>
            <div class="resp-tabs-container-item">
                <div class="prod-tab-content">
                    <h4>TAB 2 TITLE</h4>
                    <p>
                        TAB 2 CONTENT
                    </p>
                </div></div>
            <div class="resp-tabs-container-item">
                <div class="prod-tab-content">
                    <h4>TAB 3 TITLE</h4>
                    <p>
                        TAB 3 CONTENT
                    </p>
                </div>
            </div>
        </div>
    </div>

CSS

CSS

    .responsive-tab-wrapper{
        -webkit-box-shadow: 0px 3px 25px -5px rgba(0,0,0,0.75);
        -moz-box-shadow: 0px 3px 25px -5px rgba(0,0,0,0.75);
        box-shadow: 0px 3px 25px -5px rgba(0,0,0,0.75);
        margin-top: 50px;
        padding: 15px
    }
    .resp-tabs-container{
        padding: 30px;

    }    
    .resp-tabs-list {
        padding: 0;
    }

    .resp-tabs-list i {
        margin-right: 15px;
        font-size: 24px;
    }

    .resp-tabs-list li {
        cursor: pointer;
        border-bottom: solid 1px #e4eae1;
        line-height: 55px;
        padding-left: 15px;
        font-weight: 300;
        font-size: 18px;
        /* transition: all 0.5s ease; */
        -webkit-transition: all 0.5s ease;
        -moz-transition: all 0.5s ease;
        -o-transition: all 0.5s ease;
        font-family: 'Hammersmith One', sans-serif;
        text-transform: uppercase;
        border-left: solid 2px #fff;
        list-style: none;
        white-space: nowrap; 
        overflow: hidden;
        text-overflow: ellipsis;
    }

    .resp-tabs-list li:hover,
    .resp-tabs-list li.resp-tab-active,
    h3.resp-accordion:hover {
        background-color: #ffffff;
        /* border-bottom: 1px solid #BFE1B1; */
        border-left: solid 2px #3bc500;

    }



    h3.resp-tab-active,
    h3.resp-tab-active:hover {
        border-bottom: 1px solid #e7edee;
    }

    h3.resp-accordion {
        cursor: pointer;
        font-size: 18px;
        display: none;
        font-weight: 300;
        border-bottom: 1px solid #e7edee;
        margin: 0;
        line-height: 66px;
        transition: all 0.7s ease;
        -webkit-transition: all 0.7s ease;
        -moz-transition: all 0.7s ease;
        -o-transition: all 0.7s ease;
    }

    h3.resp-accordion:hover {}

    .resp-tab-content {
        display: none;
    }

    .resp-content-active,
    .resp-accordion-active {
        display: block;
    }


    /*-----------Vertical tabs-----------*/
    .resp-arrow {
        width: 0;
        height: 0;
        float: right;
        margin-top: 27px;
        margin-right: 15px;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-top: 7px solid;
    }

    h3.resp-tab-active span.resp-arrow {
        border: none;
        border-left: 5px solid transparent;
        border-right: 5px solid transparent;
        border-bottom: 7px solid;
    }

    /*-----------Accordion styles-----------*/
    h3.resp-tab-active {
        background: #dbfdcc;
        /* !important;*/
        border-color: #d3efc8;
    }

    .resp-easy-accordion h3.resp-accordion {
        display: block;
    }

    .resp-jfit {
        width: 100%;
        margin: 0px;
    }

    .resp-tab-content-active {
        display: block;
        background: #e7edee;
        padding: 0 25px 25px;
    }

    .prod-tab-content img{
        width: 300px;
        float: right;
    }

    /*Here your can change the breakpoint to set the accordion, when screen resolution changed*/
    @media only screen and (max-width: 980px) {
        ul.resp-tabs-list {
            display: none;
        }

        h3.resp-accordion {
            display: block;
            padding-left: 25px;
        }
        .resp-accordion-closed {
            display: none !important;
        }
        .prod-tab-content{
            padding: 10px;
        }
    }

jQuery

jQuery

 $(function () {
        var startItemIndex = 0;
        var tabItemContainer = ".resp-tabs-container";
        var tabItemList = $(".resp-tabs-list");
        var tabInterval;
        var tabIntervalTime = 3000; //In milliseconds
        var stopOnHover = true;

        tabItemList.find(".resp-tab-item").each(function(index,val){
            var itemHeading = $(this).html();
            $(tabItemContainer).find(".resp-tabs-container-item").eq(index).before('<h3 class="resp-accordion" data-listindex="'+index+'"><span class="resp-arrow"></span>'+itemHeading+'</h3>');
        });

        $(tabItemContainer).find(".resp-tabs-container-item h3.resp-accordion").on("click", function () {
                var itemIndex = $(this).index();
                changeIndex(itemIndex);
                clearInterval(tabInterval);
                startAutoTab();
            });

        function changeIndex(itemIndex) {
            tabItemList.find(".resp-tab-item").removeClass("resp-tab-active");
            tabItemList.find(".resp-tab-item:eq(" + itemIndex + ")").addClass("resp-tab-active");

            if($(window).width()<980){
                $(tabItemContainer).find(".resp-tabs-container-item").slideUp();
                $(tabItemContainer).find(".resp-tabs-container-item:eq(" + itemIndex + ")").stop().slideDown();
            }else{
                $(tabItemContainer).find(".resp-tabs-container-item").hide();
                $(tabItemContainer).find(".resp-tabs-container-item:eq(" + itemIndex + ")").stop().fadeIn();
            }

            $(tabItemContainer).find("h3.resp-accordion").removeClass("resp-tab-active");
            $(tabItemContainer).find("h3.resp-accordion").eq(itemIndex).addClass("resp-tab-active");

        }
        changeIndex(startItemIndex);
        tabItemList.find(".resp-tab-item").on("click", function () {
            var itemIndex = $(this).index();
            changeIndex(itemIndex);
            clearInterval(tabInterval);
            startAutoTab();
        });

        $(document).find(tabItemContainer).find("h3.resp-accordion").on("click", function () {
            var itemIndex = $(this).attr("data-listindex");
            changeIndex(itemIndex);
            clearInterval(tabInterval);
            startAutoTab();
        });
        function startAutoTab() {
            tabInterval = setInterval(function () {
                var isHovered = false;
                if(stopOnHover)
                isHovered = ($('ul.resp-tabs-list').is(":hover") || $('div.resp-tabs-container').is(":hover"));
                if (!isHovered) {
                    var totalTabs = tabItemList.find(".resp-tab-item").length;
                    if (totalTabs == ($("ul.resp-tabs-list .resp-tab-item.resp-tab-active").index() + 1)) {
                        $(".resp-tab-item").eq(0).trigger("click");
                    } else {
                        $(".resp-tab-item.resp-tab-active").next().trigger("click");
                    }
                }
            }, tabIntervalTime);
        }
        startAutoTab();
    });