bootstrap-switch

首先需要引入bootstrap的css和js文件,再引入bootstrap-switch.css和bootstrap-switch.js文件

<script type="text/javascript" src="bootstrap-switch.min.js"></script>     
<link rel="stylesheet" type="text/css" href="bootstrap-switch.min.css" /> 

下载地址:http://www.bootcss.com/p/bootstrap-switch/

html代码:

<div class="switch">
    <input type="checkbox" name="switch">
</div>

通过js实现开关的初始化:

$('[name="switch"]').bootstrapSwitch({  
        onText:"启动",  
        offText:"停止",  
        onColor:"success",  
        offColor:"info",  
        size:"small",  
        onSwitchChange:function(event,state){  
            if(state==true){  
                $(this).val("1");  
            }else{  
                $(this).val("2");  
            }  
        }  
    })  

覆盖全局属性:

$.fn.bootstrapSwitch.defaults.size = 'large';  
$.fn.bootstrapSwitch.defaults.onColor = 'success';

bootstrap-switch若想根据动态数据控制switch的状态,使用$(this).bootstrapSwitch('state',!state,true);

贴代码

 1 $(element[0]).children().bootstrapSwitch().on('switchChange.bootstrapSwitch',function(target,state){
 2         $(this).bootstrapSwitch('state',!state,true);//阻止switch状态变化
 3 
 4         //......此处省略动态获取数据的代码
 5 
 6         //如果TRUE则状态改变,否则状态不变
 7         if(...){
 8               $this.bootstrapSwitch('toggleState',true);  
 9         }
10 })    

bootstrap-switch的属性:

bootstrap-switch属性
js属性名html属性名类型描述取值范围默认值
statecheckedBoolean选中状态true、falsetrue
sizedata-sizeString开关大小null、mini、small、normal、largenull
animatedata-animateBoolean动画效果true、falsetrue
disableddisabledBoolean禁用开关ture、falsefalse
readonlyreadonlyBoolean开关状态只读,不能修改true、falsefalse
indeterminatedata-indeterminateBoolean模态true、falsefalse
inversedata-inverseBoolean颠倒开关顺序true、falsefalse
radioAllOffdata-radio-all-offBoolean允许单选按钮被用户取消选中true、falsefalse
onColordata-on-colorString左侧开关颜色primary、info、success、warning、danger、defaultprimary
offColordata-off-colorString右侧开关颜色primary、info、success、warning、danger、defaultdefault
onTextdata-on-textString左侧开关显示文本StringON
offTextdata-off-textString右侧开关显示文本StringOFF
labelTextdata-label-textString开关中间显示文本String&nbsp;
handleWidthdata-handle-widthString|Number开关左右2侧的宽度String|Numberauto
labelWidthdata-label-widthString|Number开关中间的宽度String|Numberauto
baseClassdata-base-classString开关基础样式Stringbootstrap-switch
wrapperClassdata-wrapper-classString | Array元素样式容器String | Arraywrapper
onInitfunction初始化开关Functionfunction(event,state){}
onSwitchChangefunction当开关状态改变时触发Functionfunction(event,state){}