search
HomeWeb Front-endBootstrap TutorialLet's learn about the tab tab in Bootstrap

This article will take you through the tab tab in Bootstrap. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Let's learn about the tab tab in Bootstrap

Tabs Tabs are a very common function in the Web. When the user clicks on the menu item, the corresponding content can be switched out. This article will introduce the Bootstrap tab in detail [Related recommendation: "bootstrap tutorial"]

Basic usage

The tabs in the Bootstrap framework mainly include It consists of two parts: 1. The tab menu component, corresponding to Bootstrap’s nav-tabs

2. The switchable tab panel component, usually tab-pane in Bootstrap Represents

In the Bootstrap framework, the tab nav-tabs have styles, and the panel content tab-pane is hidden, and only the current panel content is displayed

.tab-content > .tab-pane {
    display: none;
}
.tab-content > .active {
    display: block;
}

 Tab Define the data attribute to trigger the switching effect. Of course, the prerequisite is to load bootstrap.js or tab.js first. Declarative triggering tabs need to meet the following requirements:

1. Set data-toggle="tab"

in the tab navigation link 2. And set data-target=" corresponding The selector of the content panel (usually ID)"; if it is a link, you can also use href="the selector of the corresponding content panel (usually ID)". The main function is that the user can find the selector corresponding to it when clicking The panel content tab-pane.

3. The panel content is uniformly placed in the tab-content container, and each content panel tab-pane needs to set an independent selector (preferably ID) with the data-target or data-target in the tab. The value of href matches

<!-- 选项卡菜单-->
<ul id="myTab" class="nav nav-tabs" role="tablist">
    <li class="active"><a href="#bulletin" role="tab" data-toggle="tab">公告</a></li>
    <li><a href="#rule" role="tab" data-toggle="tab">规则</a></li>
    <li><a href="#forum" role="tab" data-toggle="tab">论坛</a></li>
    <li><a href="#security" role="tab"  data-toggle="tab">安全</a></li>
    <li><a href="#welfare" role="tab" data-toggle="tab">公益</a></li>
</ul>
<!-- 选项卡面板 -->
<div id="myTabContent" class="tab-content">
    <div class="tab-pane active" id="bulletin">公告内容面板</div>
    <div class="tab-pane " id="rule">规则内容面板</div>
    <div class="tab-pane " id="forum">论坛内容面板</div>
    <div class="tab-pane " id="security">安全内容面板</div>
    <div class="tab-pane " id="welfare">公益内容面板</div>
</div>

Lets learn about the tab tab in Bootstrap

[Fade-in effect]

In order to make the hiding and display of the panel more effective during the switching process Smooth, you can add the class name fade in the panel to produce a gradual effect.

When adding the fade style, the initial default displayed content panel must be added with the in class name, otherwise the user will not be able to see its content

<!-- 选项卡菜单-->
<ul id="myTab" class="nav nav-tabs" role="tablist">
    <li class="active"><a href="#bulletin" role="tab" data-toggle="tab">公告</a></li>
    <li><a href="#rule" role="tab" data-toggle="tab">规则</a></li>
    <li><a href="#forum" role="tab" data-toggle="tab">论坛</a></li>
    <li><a href="#security" role="tab"  data-toggle="tab">安全</a></li>
    <li><a href="#welfare" role="tab" data-toggle="tab">公益</a></li>
</ul>
<!-- 选项卡面板 -->
<div id="myTabContent" class="tab-content">
    <div class="tab-pane fade in active" id="bulletin">公告内容面板</div>
    <div class="tab-pane fade" id="rule">规则内容面板</div>
    <div class="tab-pane fade" id="forum">论坛内容面板</div>
    <div class="tab-pane fade" id="security">安全内容面板</div>
    <div class="tab-pane fade" id="welfare">公益内容面板</div>
</div>

Lets learn about the tab tab in Bootstrap

【Capsule Tab】

In Bootstrap, in addition to allowing nav-tabs to have the tab switching function, the capsule nav-pills navigation can also have the tab function. . Just replace nav-tabs with nav-pills. Another key point is to replace

data-toggle="tab"

with data-toggle="pill"<pre class='brush:php;toolbar:false;'>&lt;!-- 选项卡菜单--&gt; &lt;ul id=&quot;myTab&quot; class=&quot;nav nav-pills&quot; role=&quot;tablist&quot;&gt; &lt;li class=&quot;active&quot;&gt;&lt;a href=&quot;#bulletin&quot; role=&quot;tab&quot; data-toggle=&quot;pill&quot;&gt;公告&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#rule&quot; role=&quot;tab&quot; data-toggle=&quot;pill&quot;&gt;规则&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#forum&quot; role=&quot;tab&quot; data-toggle=&quot;pill&quot;&gt;论坛&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#security&quot; role=&quot;tab&quot; data-toggle=&quot;pill&quot;&gt;安全&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href=&quot;#welfare&quot; role=&quot;tab&quot; data-toggle=&quot;pill&quot;&gt;公益&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;!-- 选项卡面板 --&gt; &lt;div id=&quot;myTabContent&quot; class=&quot;tab-content&quot;&gt; &lt;div class=&quot;tab-pane fade in active&quot; id=&quot;bulletin&quot;&gt;公告内容面板&lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;rule&quot;&gt;规则内容面板&lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;forum&quot;&gt;论坛内容面板&lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;security&quot;&gt;安全内容面板&lt;/div&gt; &lt;div class=&quot;tab-pane fade&quot; id=&quot;welfare&quot;&gt;公益内容面板&lt;/div&gt; &lt;/div&gt;</pre>

Lets learn about the tab tab in Bootstrap

JS trigger

In addition to setting data-toggle in HTML to trigger tabs, it can also be called directly through JavaScript.

Call the

tab("show")

method in the click event of each link to display the corresponding tab panel content. For the above example, delete the custom data-toggle="tab" or data-toggle="pill" attributes in HTML, and then call <pre class='brush:php;toolbar:false;'>$(function(){ $(&quot;#myTab a&quot;).click(function(e){ e.preventDefault(); $(this).tab(&quot;show&quot;); }); })</pre><pre class="brush:php;toolbar:false">&lt;!-- 选项卡菜单--&gt; </pre> <ul>     <li><a>公告</a></li>     <li><a>规则</a></li>     <li><a>论坛</a></li>     <li><a>安全</a></li>     <li><a>公益</a></li> </ul> <!-- 选项卡面板 --> <div>     <div>公告内容面板</div>     <div>规则内容面板</div>     <div>论坛内容面板</div>     <div>安全内容面板</div>     <div>公益内容面板</div> </div> <script> $(function(){ $(&quot;#myTab a&quot;).click(function(e){ e.preventDefault(); $(this).tab(&quot;show&quot;); }); }) </script>

# through the following script Lets learn about the tab tab in Bootstrap##【Event Subscription】

show.bs.tab        show方法调用之后立即触发该事件
shown.bs.tab      此事件在tab已经显示出来(并且同时在 CSS 过渡效果完成)之后被触发
hide.bs.tab        hide方法调用之后立即触发该事件。
hidden.bs.tab     此事件在tab被隐藏(并且同时在 CSS 过渡效果完成)之后被触发

<!-- 选项卡菜单-->
    
公告内容面板
    
规则内容面板
    
论坛内容面板
    
安全内容面板
    
公益内容面板
<script> $(function(){ $("#myTab a").click(function(e){ e.preventDefault(); $(this).tab("show"); }); $("#myTab").on("show.bs.tab",function(e){ $(e.target).css(&#39;outline&#39;,&#39;1px solid black&#39;); }).on("hide.bs.tab",function(e){ $(e.target).css(&#39;outline&#39;,&#39;none&#39;); }) }) </script>

Lets learn about the tab tab in BootstrapJS Source Code

【1】IIFE

Use the immediate call function to prevent the code in the plug-in from leaking, thus forming a closed loop, and it can only be expanded from jQuery’s fn

+function ($) {
    //使用es5严格模式
    'use strict';
    //
}(window.jQuery);
[2] Initial settings

var Tab = function (element) {
    //指定当前元素
    this.element = $(element)
  }
  //版本号为3.3.7
  Tab.VERSION = '3.3.7'
  //动画时间为150ms
  Tab.TRANSITION_DURATION = 150
[3 】Plug-in core code

//show()方法用于触发show事件,调用activate原型方法,触发shown事件
  Tab.prototype.show = function () {
    //当前tab
    var $this    = this.element
    //找到最近的ul
    var $ul      = $this.closest('ul:not(.dropdown-menu)')
    //找到data-target值
    var selector = $this.data('target')
    //如果data-target值不存在,查找href值
    if (!selector) {
      selector = $this.attr('href')
      //IE7特殊处理
      selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') 
    }
    //如果当前tab已经是活动状态了,即父元素li上已经有active样式的话,直接返回
    if ($this.parent('li').hasClass('active')) return
    //找到上一个元素,即上一个带有active样式的li里的a元素
    var $previous = $ul.find('.active:last a')
    //设置hide事件
    var hideEvent = $.Event('hide.bs.tab', {
      relatedTarget: $this[0]
    })
    //设置show事件
    var showEvent = $.Event('show.bs.tab', {
      relatedTarget: $previous[0]
    })
    //触发hide事件及show事件
    $previous.trigger(hideEvent)
    $this.trigger(showEvent)
    //如果自定义回调中阻止了默认行为,则不再继续处理
    if (showEvent.isDefaultPrevented() || hideEvent.isDefaultPrevented()) return
    //要激活显示的面板,即target或href里的值所对应的元素
    var $target = $(selector)
    //高亮显示当前tab
    this.activate($this.closest('li'), $ul)
    //显示对应的面板,并在回调里触发hidden及shown事件
    this.activate($target, $target.parent(), function () {
      $previous.trigger({
        type: 'hidden.bs.tab',
        relatedTarget: $this[0]
      })
      $this.trigger({
        type: 'shown.bs.tab',
        relatedTarget: $previous[0]
      })
    })
  }
  //active样式的应用,面板的显示和隐藏,以及tab的高亮与反高亮
  Tab.prototype.activate = function (element, container, callback) {
    //查找当前容器所有有active样式的元素
    var $active    = container.find('> .active')
    //判断是使用回调还是动画
    var transition = callback
      && $.support.transition
      && ($active.length && $active.hasClass('fade') || !!container.find('> .fade').length)

    function next() {
      $active
        //去除其他元素的active样式
        .removeClass('active')
        //包括li元素里面的下拉菜单里的active样式也要去除
        .find('> .dropdown-menu > .active')
          .removeClass('active')
        .end()
        .find('[data-toggle="tab"]')
          .attr('aria-expanded', false)

      element
        //给当前被单击的元素添加active高亮样式
        .addClass('active')
        .find('[data-toggle="tab"]')
          .attr('aria-expanded', true)

      if (transition) {
        //如果支持动画,就重绘页面
        element[0].offsetWidth 
        //并添加in样式,去除透明
        element.addClass('in')
      } else {
        //否则删除fade
        element.removeClass('fade')
      }
      //如果单击的是下拉菜单里的项目
      if (element.parent('.dropdown-menu').length) {
        element
          //打到最近的li.dropdown元素进行高亮
          .closest('li.dropdown')
            .addClass('active')
          .end()
          .find('[data-toggle="tab"]')
            .attr('aria-expanded', true)
      }
      //如果有回调就执行回调
      callback && callback()
    }
    //如果支持动画
    $active.length && transition ?
      $active
        //在动画结束后执行next()
        .one('bsTransitionEnd', next)
        .emulateTransitionEnd(Tab.TRANSITION_DURATION) :
      next()

    $active.removeClass('in')
  }
【4】jQuery plug-in definition

function Plugin(option) {
    //根据选择器,遍历所有符合规则的元素
    return this.each(function () {
      var $this = $(this)
      //获取自定义属性bs.tab的值
      var data  = $this.data('bs.tab')
      //如果值不存在,则将Tab实例设置为bs.tab值
      if (!data) $this.data('bs.tab', (data = new Tab(this)))
      //如果option传递了string,则表示要执行某个方法  
      if (typeof option == 'string') data[option]()
    })
  }

  var old = $.fn.tab
  //保留其他库的$.fn.tab代码(如果定义的话),以便在noConflict之后可以继续使用该老代码
  $.fn.tab             = Plugin
  //重设插件构造器,可以通过该属性获取插件的真实类函数
  $.fn.tab.Constructor = Tab
【5】Anti-conflict processing

$.fn.tab.noConflict = function () {
     //恢复以前的旧代码
    $.fn.tab = old
    //将$.fn.tab.noConflict()设置为Bootstrap的Tab插件
    return this
  }
【6】Binding trigger event

var clickHandler = function (e) {
    //阻止默认行为
    e.preventDefault()
    //触发show()方法
    Plugin.call($(this), 'show')
  }

  $(document)
    //在document上绑定单击事件
    .on('click.bs.tab.data-api', '[data-toggle="tab"]', clickHandler)
    .on('click.bs.tab.data-api', '[data-toggle="pill"]', clickHandler)
For more programming-related knowledge, please visit:

programming video

! !

The above is the detailed content of Let's learn about the tab tab in Bootstrap. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Integrating Bootstrap Styles in React: Methods and TechniquesIntegrating Bootstrap Styles in React: Methods and TechniquesApr 17, 2025 am 12:04 AM

Integrating Bootstrap in React projects can be done in two ways: 1) introduced using CDN, suitable for small projects or rapid prototyping; 2) installation using npm package manager, suitable for scenarios that require deep customization. With these methods, you can quickly build beautiful and responsive user interfaces in React.

Bootstrap in React: Advantages and Best PracticesBootstrap in React: Advantages and Best PracticesApr 16, 2025 am 12:17 AM

Advantages of integrating Bootstrap into React projects include: 1) rapid development, 2) consistency and maintainability, and 3) responsive design. By directly introducing CSS files or using the React-Bootstrap library, you can use Bootstrap's components and styles efficiently in your React project.

Bootstrap: A Quick Guide to Web FrameworksBootstrap: A Quick Guide to Web FrameworksApr 15, 2025 am 12:10 AM

Bootstrap is a framework developed by Twitter to help quickly build responsive, mobile-first websites and applications. 1. Ease of use and rich component libraries make development faster. 2. The huge community provides support and solutions. 3. Introduce and use class names to control styles through CDN, such as creating responsive grids. 4. Customizable styles and extension components. 5. Advantages include rapid development and responsive design, while disadvantages are style consistency and learning curve.

Breaking Down Bootstrap: What It Is and Why It MattersBreaking Down Bootstrap: What It Is and Why It MattersApr 14, 2025 am 12:05 AM

Bootstrapisafree,open-sourceCSSframeworkthatsimplifiesresponsiveandmobile-firstwebsitedevelopment.Itofferspre-styledcomponentsandagridsystem,streamliningthecreationofaestheticallypleasingandfunctionalwebdesigns.

Bootstrap: Making Web Design EasierBootstrap: Making Web Design EasierApr 13, 2025 am 12:10 AM

What makes web design easier is Bootstrap? Its preset components, responsive design and rich community support. 1) Preset component libraries and styles allow developers to avoid writing complex CSS code; 2) Built-in grid system simplifies the creation of responsive layouts; 3) Community support provides rich resources and solutions.

Bootstrap's Impact: Accelerating Web DevelopmentBootstrap's Impact: Accelerating Web DevelopmentApr 12, 2025 am 12:05 AM

Bootstrap accelerates web development, and by providing predefined styles and components, developers can quickly build responsive websites. 1) It shortens development time, such as completing the basic layout within a few days in the project. 2) Through Sass variables and mixins, Bootstrap allows custom styles to meet specific needs. 3) Using the CDN version can optimize performance and improve loading speed.

Understanding Bootstrap: Core Concepts and FeaturesUnderstanding Bootstrap: Core Concepts and FeaturesApr 11, 2025 am 12:01 AM

Bootstrap is an open source front-end framework, and its main function is to help developers quickly build responsive websites. 1) It provides predefined CSS classes and JavaScript plug-ins to facilitate the implementation of complex UI effects. 2) The working principle of Bootstrap relies on its CSS and JavaScript components to realize responsive design through media queries. 3) Examples of usage include basic usage, such as creating buttons, and advanced usage, such as custom styles. 4) Common errors include misspelling of class names and incorrectly introducing files. It is recommended to use browser developer tools to debug. 5) Performance optimization can be achieved through custom build tools, best practices include predefined using semantic HTML and Bootstrap

Bootstrap Deep Dive: Responsive Design & Advanced Layout TechniquesBootstrap Deep Dive: Responsive Design & Advanced Layout TechniquesApr 10, 2025 am 09:35 AM

Bootstrap implements responsive design through grid systems and media queries, making the website adapted to different devices. 1. Use a predefined class (such as col-sm-6) to define the column width. 2. The grid system is based on 12 columns, and it is necessary to note that the sum does not exceed 12. 3. Use breakpoints (such as sm, md, lg) to define the layout under different screen sizes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool