bootstrap之buttonJs

本文介绍了Bootstrap中的button.js组件,详细解析了其核心功能包括按钮状态切换、单选和多选按钮处理等,并提供了示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、前言

上节介绍了button模块的样式,这节介绍button.js。

二、源码

 /* ========================================================================
  * Bootstrap: button.js v3.3.7(按钮)
  * http://getbootstrap.com/javascript/#buttons
  * ========================================================================
  * Copyright 2011-2016 Twitter, Inc.
  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  * ======================================================================== */
 +function ($) {
   'use strict';

   // BUTTON PUBLIC CLASS DEFINITION
   // ==============================
   var Button = function (element, options) {
     this.$element  = $(element);
     this.options   = $.extend({}, Button.DEFAULTS, options);
     this.isLoading = false
   };

   Button.VERSION  = '3.3.7';

   Button.DEFAULTS = {
     loadingText: 'loading...'
   };

   // 处理按钮状态
   Button.prototype.setState = function (state) {
     var d    = 'disabled';
     var $el  = this.$element;
     var val  = $el.is('input') ? 'val' : 'html';
     var data = $el.data();

     state += 'Text';

     // 存储按钮初始值,为了以后重置
     if (data.resetText == null) $el.data('resetText', $el[val]());

     // push to event loop to allow forms to submit
     setTimeout($.proxy(function () {
       $el[val](data[state] == null ? this.options[state] : data[state]);

       if (state == 'loadingText') {
         this.isLoading = true;
         $el.addClass(d).attr(d, d).prop(d, true)
       } else if (this.isLoading) {
         this.isLoading = false;
         $el.removeClass(d).removeAttr(d).prop(d, false)
       }
     }, this), 0)
   };

   // 处理单选、多选
   Button.prototype.toggle = function () {
     var changed = true;
     var $parent = this.$element.closest('[data-toggle="buttons"]');

     if ($parent.length) {
       var $input = this.$element.find('input');
       if ($input.prop('type') == 'radio') {
         if ($input.prop('checked')) changed = false;
         $parent.find('.active').removeClass('active');
         this.$element.addClass('active')
       } else if ($input.prop('type') == 'checkbox') {
         // 处理checkbox默认被checked情况,这个时候再被选中只是改变下样式
         if (($input.prop('checked')) !== this.$element.hasClass('active')) changed = false;
         this.$element.toggleClass('active')
       }
       $input.prop('checked', this.$element.hasClass('active'));
       if (changed) $input.trigger('change')
     } else {
       this.$element.attr('aria-pressed', !this.$element.hasClass('active'));
       this.$element.toggleClass('active')
     }
   };

   // BUTTON PLUGIN DEFINITION
   // ========================
   function Plugin(option) {
     return this.each(function () {
       var $this   = $(this);
       var data    = $this.data('bs.button');
       var options = typeof option == 'object' && option;

       if (!data) $this.data('bs.button', (data = new Button(this, options)));

       if (option == 'toggle') data.toggle();
       else if (option) data.setState(option)
     })
   }

   var old = $.fn.button;

   $.fn.button             = Plugin;
   $.fn.button.Constructor = Button;

   // BUTTON NO CONFLICT
   // ==================
   $.fn.button.noConflict = function () {
     $.fn.button = old;
     return this
   };

   // BUTTON DATA-API
   // ===============
   $(document)
     .on('click.bs.button.data-api', '[data-toggle^="button"]', function (e) {
       var $btn = $(e.target).closest('.btn');
       Plugin.call($btn, 'toggle');
       if (!($(e.target).is('input[type="radio"], input[type="checkbox"]'))) {
         // Prevent double click on radios, and the double selections (so cancellation) on checkboxes
         e.preventDefault();
         // The target component still receive the focus
         if ($btn.is('input,button')) $btn.trigger('focus');
         else $btn.find('input:visible,button:visible').first().trigger('focus')
       }
     })
     .on('focus.bs.button.data-api blur.bs.button.data-api', '[data-toggle^="button"]', function (e) {
       $(e.target).closest('.btn').toggleClass('focus', /^focus(in)?$/.test(e.type))
     })

 }(jQuery);

三、应用 & 源码分析

1、应用
 // 切换状态
 $("#loaddingBtn").click(function () {
   $(this).button("loading");
 });

 // 复选框
 <div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="checkbox"> 选项 1
    </label>
    <label class="btn btn-primary">
        <input type="checkbox"> 选项 2
    </label>
    <label class="btn btn-primary">
        <input type="checkbox"> 选项 3
    </label>
 </div>

 // 单选框
 <div class="btn-group" data-toggle="buttons">
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option1"> 选项 1
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option2"> 选项 2
    </label>
    <label class="btn btn-primary">
        <input type="radio" name="options" id="option3"> 选项 3
    </label>
 </div> 
2、源码分析

1、setState
设置按钮状态,处理按钮状态切换
2、toggle
切换单选、多选按钮激活状态
3、[data-toggle^="button"]
应用正则表达式监听data-toggle=”button”和data-toggle=”buttons”元素

Ext.onReady(function(){ // This function renders a block of buttons function renderButtons(title){ Ext.getBody().createChild({tag: 'h2', html: title}); new ButtonPanel( 'Text Only', [{ text: 'Add User' },{ text: 'Add User', scale: 'medium' },{ text: 'Add User', scale: 'large' }] ); new ButtonPanel( 'Icon Only', [{ iconCls: 'add16' },{ iconCls: 'add24', scale: 'medium' },{ iconCls: 'add', scale: 'large' }] ); new ButtonPanel( 'Icon and Text (left)', [{ text: 'Add User', iconCls: 'add16' },{ text: 'Add User', iconCls: 'add24', scale: 'medium' },{ text: 'Add User', iconCls: 'add', scale: 'large' }] ); new ButtonPanel( 'Icon and Text (top)', [{ text: 'Add User', iconCls: 'add16', iconAlign: 'top' },{ text: 'Add User', iconCls: 'add24', scale: 'medium', iconAlign: 'top' },{ text: 'Add User', iconCls: 'add', scale: 'large', iconAlign: 'top' }] ); new ButtonPanel( 'Icon and Text (right)', [{ text: 'Add User', iconCls: 'add16', iconAlign: 'right' },{ text: 'Add User', iconCls: 'add24', scale: 'medium', iconAlign: 'right' },{ text: 'Add User', iconCls: 'add', scale: 'large', iconAlign: 'right' }] ); new ButtonPanel( 'Icon and Text (bottom)', [{ text: 'Add User', iconCls: 'add16', iconAlign: 'bottom' },{ text: 'Add User', iconCls: 'add24', scale: 'medium', iconAlign: 'bottom' },{ text: 'Add User', iconCls: 'add', scale: 'large', iconAlign: 'bottom' }] ); } renderButtons('Normal Buttons'); ButtonPanel.override({ enableToggle: true }); renderButtons('Toggle Buttons'); ButtonPanel.override({ enableToggle : undefined, menu : {items: [{text:'Menu Item 1'},{text:'Menu Item 2'},{text:'Menu Item 3'}]} }); renderButtons('Menu Buttons'); ButtonPanel.override({ split: true, defaultType: 'splitbutton' }); renderButtons('Split Buttons'); ButtonPanel.override({ split: false, defaultType: 'button', arrowAlign: 'bottom' }); renderButtons('Menu Buttons (Arrow on bottom)'); ButtonPanel.override({ split: true, defaultType: 'splitbutton' }); renderButtons('Split Buttons (Arrow on bottom)'); }); // Helper class for organizing the buttons ButtonPanel = Ext.extend(Ext.Panel, { layout:'table', defaultType: 'button', baseCls: 'x-plain', cls: 'btn-panel', renderTo : 'docbody', menu: undefined, split: false, layoutConfig: { columns:3 }, constructor: function(desc, buttons){ // apply test configs for(var i = 0, b; b = buttons[i]; i++){ b.menu = this.menu; b.enableToggle = this.enableToggle; b.split = this.split; b.arrowAlign = this.arrowAlign; } var items = [{ xtype: 'box', autoEl: {tag: 'h3', html: desc, style:"padding:15px 0 3px;"}, colspan: 3 }].concat(buttons); ButtonPanel.superclass.constructor.call(this, { items: items }); } });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值