search
HomeWeb Front-endBootstrap TutorialDetailed explanation of button components in Bootstrap

This article will take you to learn more about the button component in Bootstrap. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of button components in Bootstrap

The button plug-in provides a set of functions that can control multiple states of the button, such as the disabled state of the button, the loading state, and the normal state. Status etc. This article will introduce the Bootstrap button plug-in in detail

Loading status

You can design status prompts through buttons. When the button is clicked, the loading status information will be displayed. For example, clicking the "Load" button will trigger the loading status of the button

By adding data-loading-text="Loading..." you can set the loading status for the button, But Starting from v3.3.5, this feature is no longer recommended and has been deleted in v4 version

 [Note] If data-loading is not set -text, when the button text is in the Loading state, the default display is 'loading...'

<button>加载</button>
<script>
$(function(){
    $("#loaddingBtn").click(function () {
        var $btn = $(this).button("loading");
        setTimeout(function(){
            $btn.button(&#39;reset&#39;)
        },1000);
      });
});    
</script>

Detailed explanation of button components in Bootstrap

[Related recommendations: "bootstrap tutorial》】

Simulation radio button

Simulation radio button is a set of buttons to implement a single selection operation. Using a button group to simulate a radio button group can make the design more personalized and customize a more beautiful radio button group

In the button plug-in in the Bootstrap framework, you can customize attributes for the button group data-toggle="buttons"

<div>
    <label>
        <input>男
    </label>
    <label>
        <input>女
    </label>
</div>

Detailed explanation of button components in Bootstrap

Simulate multiple selection

Use button groups to simulate multiple selections Select buttons are the same as simulated radio buttons and have the same effect. They are also achieved by customizing data-toggle="buttons" on the button group. The only difference is to replace input[type="radio"] with input[type="checkbox"]

<div>
    <label>
        <input>电影
    </label>
    <label>
        <input>音乐
    </label>
    <label>
        <input>游戏
    </label>
    <label>
        <input>摄影
    </label>
</div>

Detailed explanation of button components in Bootstrap

button status

Using the data-toggle attribute can also activate the behavior state of the button to switch the state between activated and inactive. The button is activated when clicked, and clicked again to restore the button to its default state

<button>有状态的按钮</button>
<button>普通按钮</button>

Detailed explanation of button components in Bootstrap

JS trigger

The button plug-in can By calling the button function and then passing in specific parameters to the button function, different effects can be achieved. Two of the parameters are fixed, namely toggle and reset. Others can be defined at will:

$("#mybutton").button("toggle");//反转按钮状态
$("#mybutton").button("reset");//重置按钮状态
$("#mybutton").button("任意字符参数名");//替换 data-任意字符参数名-text 的属性值为“按钮上显示的文本值
<button class="btn btn-primary" data-complete-text="加载完成" type="button" id="mybutton">加载</button>
<script>
$(function(){
    $("#mybutton").click(function () {
        var $btn = $(this).button("loading");
        setTimeout(function(){
            $btn.button(&#39;complete&#39;);
        },1000);
      });
});    
</script>

Detailed explanation of button components in Bootstrap

JS source code

[1]IIFE

Use immediate call functions to prevent code in the plug-in leaked, thus forming a closed loop, and can only be expanded from jQuery's fn

+function ($) {
    //使用es5严格模式
    &#39;use strict&#39;;
    //
}(window.jQuery);

[2]Initial settings

var Button = function (element, options) {
    //要触发的元素
    this.$element  = $(element)
    //合并参数
    this.options   = $.extend({}, Button.DEFAULTS, options)
    //是否是加载状态
    this.isLoading = false
  }
  //版本号为3.3.7
  Button.VERSION  = &#39;3.3.7&#39;
  //默认loadinf时的文本内容为&#39;loading...&#39;
  Button.DEFAULTS = {
    loadingText: &#39;loading...&#39;
  }

[3]Plug-in core code

//设置按钮状态的方法
  Button.prototype.setState = function (state) {
    //按钮需要禁用时使用它,先赋值一个临时变量
    var d    = &#39;disabled&#39;
    //当前元素
    var $el  = this.$element
    //如果是input,则使用val获取值,否则,使用html获取值
    var val  = $el.is(&#39;input&#39;) ? &#39;val&#39; : &#39;html&#39;
    //获取当前元素的自定义属性,所有以data-开头的属性
    var data = $el.data()
    //组装需要用到的属性,如传入loading,则组装成loadingText
    state += &#39;Text&#39;
    //如果data里不包含data-reset-text值,则将当前元素的值临时存放,以便过后再恢复使用它
    if (data.resetText == null) $el.data(&#39;resetText&#39;, $el[val]())

    //不阻止事件,以允许表单的提交
    setTimeout($.proxy(function () {
      //给元素赋值,如果是元素默认没有值,则从options里查询,否则,从自定义属性里查询
      $el[val](data[state] == null ? this.options[state] : data[state])
      //如果传入的是loading
      if (state == &#39;loadingText&#39;) {
        //设置加载状态为true
        this.isLoading = true
        //禁用该元素(即添加disabled样式和disabled属性)
        $el.addClass(d).attr(d, d).prop(d, true)
      } else if (this.isLoading) {
        this.isLoading = false
        //如果不是,则删除disabled样式和disabled属性
        $el.removeClass(d).removeAttr(d).prop(d, false)
      }
    }, this), 0)
  }
  //切换按钮状态
  Button.prototype.toggle = function () {
    //设置change标记
    var changed = true
    //查找带有[data-toggle="buttons"]属性的最近父元素
    var $parent = this.$element.closest(&#39;[data-toggle="buttons"]&#39;)
    //如果父元素存在
    if ($parent.length) {
      //查找触发元素内是否存在input元素
      var $input = this.$element.find(&#39;input&#39;)
      //如果是单选按钮
      if ($input.prop(&#39;type&#39;) == &#39;radio&#39;) {
        //如果被选中,则设置changed为false
        if ($input.prop(&#39;checked&#39;)) changed = false
        //查找同级元素是否有active样式,如果有,则删除active样式
        $parent.find(&#39;.active&#39;).removeClass(&#39;active&#39;)
        //给当前元素添加active样式
        this.$element.addClass(&#39;active&#39;)
      //如果是多选按钮
      } else if ($input.prop(&#39;type&#39;) == &#39;checkbox&#39;) {
        //如果多选按钮选中了,但元素没有active样式
        //或者多选按钮没有选中,但元素却有active样式,则设置changed为false
        if (($input.prop(&#39;checked&#39;)) !== this.$element.hasClass(&#39;active&#39;)) changed = false
        //重置元素的active样式
        this.$element.toggleClass(&#39;active&#39;)
      }
      //将多选按钮的checked设置为是否有active样式
      $input.prop(&#39;checked&#39;, this.$element.hasClass(&#39;active&#39;))
      //如果changed为true,则触发change事件
      if (changed) $input.trigger(&#39;change&#39;)
    } else {
      this.$element.attr(&#39;aria-pressed&#39;, !this.$element.hasClass(&#39;active&#39;))
      //重置元素的active样式
      this.$element.toggleClass(&#39;active&#39;)
    }
  }

【4】jQuery plug-in definition

function Plugin(option) {
    //根据选择器,遍历所有符合规则的元素
    return this.each(function () {
      var $this   = $(this)
      //获取自定义属性bs.button的值
      var data    = $this.data(&#39;bs.button&#39;)
      var options = typeof option == &#39;object&#39; && option
      //如果值不存在,则将Button实例设置为bs.button值
      if (!data) $this.data(&#39;bs.button&#39;, (data = new Button(this, options)))
      //如果option是toggle,则直接调用该方法  
      if (option == &#39;toggle&#39;) data.toggle()
      //否则调用setState()方法
      else if (option) data.setState(option)
    })
  }

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

【5】Anti-conflict processing

$.fn.button.noConflict = function () {
    //恢复以前的旧代码
    $.fn.button = old
    //将$.fn.button.noConflict()设置为Bootstrap的Tab插件
    return this
  }

【6】Binding trigger events

$(document)
    //查询所有以button开头,data-toggle属性的值,绑定click事件
    .on(&#39;click.bs.button.data-api&#39;, &#39;[data-toggle^="button"]&#39;, function (e) {
      //查找当前单击对象的最近的有btn样式的父元素
      var $btn = $(e.target).closest(&#39;.btn&#39;)
      Plugin.call($btn, &#39;toggle&#39;)
      //如果单击对象不是单选或多选按钮
      if (!($(e.target).is(&#39;input[type="radio"], input[type="checkbox"]&#39;))) {
        //阻止默认行为
        e.preventDefault()
        //如果$btn是单选或多选按钮,触发focus事件
        if ($btn.is(&#39;input,button&#39;)) $btn.trigger(&#39;focus&#39;)
        //否则,找到子元素中的第一个具有visible状态的input或button,触发focus事件
        else $btn.find(&#39;input:visible,button:visible&#39;).first().trigger(&#39;focus&#39;)
      }
    })
    //查询所有以button开头,data-toggle属性的值,绑定focus事件
    .on(&#39;focus.bs.button.data-api blur.bs.button.data-api&#39;, &#39;[data-toggle^="button"]&#39;, function (e) {
      $(e.target).closest(&#39;.btn&#39;).toggleClass(&#39;focus&#39;, /^focus(in)?$/.test(e.type))
    })

For more programming-related knowledge, please visit:Introduction to Programming! !

The above is the detailed content of Detailed explanation of button components 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
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.

Bootstrap Interview Questions: Land Your Dream Front-End JobBootstrap Interview Questions: Land Your Dream Front-End JobApr 09, 2025 am 12:14 AM

Bootstrap is an open source front-end framework for rapid development of responsive websites and applications. 1. It provides the advantages of responsive design, consistent UI components and rapid development. 2. The grid system uses flexbox layout, based on 12-column structure, and is implemented through classes such as .container, .row and .col-sm-6. 3. Custom styles can be implemented by modifying SASS variables or overwriting CSS. 4. Commonly used JavaScript components include modal boxes, carousel diagrams and folding. 5. Optimization performance can be achieved by loading only necessary components, using CDN, and compressing merge files.

Bootstrap & JavaScript Integration: Dynamic Features & FunctionalityBootstrap & JavaScript Integration: Dynamic Features & FunctionalityApr 08, 2025 am 12:10 AM

Bootstrap and JavaScript can be seamlessly integrated to give web pages dynamic functionality. 1) Use JavaScript to manipulate Bootstrap components, such as modal boxes and navigation bars. 2) Ensure jQuery loads correctly and avoid common integration problems. 3) Achieve complex user interaction and dynamic effects through event monitoring and DOM operations.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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