bootstrapSwitch是一个很美观的切换控件,官网上对它的介绍也很详细。下面通过几个demo快速上手bootstrapSwitch。
首先,引用相应的js和css文件,把checkbox放进class为“switch”的div中,再在js中初始化
$('#mySwitch input').bootstrapSwitch();
就可以使用bootstrapSwitch了。
其中input有两个属性 data-on-text 和data-off-text,分别为切换时显示的文字,这里设置为YES和NO。代码如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>this is a bootstrap-switch test</title>
<script src="jquery-2.2.4.js"></script>
<script src="bootstrap.js"></script>
<script src="bootstrap-switch.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-switch.css"/>
<script type="text/javascript">
$(function(){
$('#mySwitch input').bootstrapSwitch();
})
</script>
</head>
<body>
<div class="switch" id="mySwitch">
<input type="checkbox" checked data-on-text="YES" data-off-text="NO"/>
</div>
</body>
</html>
也可以用js设置这两个属性,选中input元素后,通过方法bootstrapSwitch({attribute:value}) 修改属性。代码如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>this is a bootstrap-switch test</title>
<script src="jquery-2.2.4.js"></script>
<script src="bootstrap.js"></script>
<script src="bootstrap-switch.js"></script>
<link rel="stylesheet" type="text/css" href="bootstrap.css"/>
<link rel="stylesheet" type="text/css" href="bootstrap-switch.css"/>
<script type="text/javascript">
$(function(){
$('#mySwitch input').bootstrapSwitch({
onText:'On',
offText:'Off'
});
})
</script>
</head>
<body>
<br>
<div class="switch" id="mySwitch">
<input type="checkbox" checked data-on-text="YES" data-off-text="NO"/>
</div>
</body>
</html>
这里在HTML和js中都修改这两个属性,那么最后以谁为准呢?显然是js,$(function(){})在dom加载完后再执行,js会覆盖HTML中的属性配置。
当然,bootstrapSwitch不可能只有这两个属性,更多属性点击这里:
http://www.bootstrap-switch.org/options.html
注意,无论在HTML还是js中修改其属性,都是对input元素进行修改,对外层div的操作是无效的。
下面来说说bootstrapSwitch的方法。在其官方网站上有这么一句话:
In Bootstrap Switch, every option is also a method
也就是说以上对属性的配置都有调用方法
比如,switch有两种state,true或false,js可以用bootstrapSwitch(attribute,value)的方法指定为某一状态:
$('#mySwitch input').bootstrapSwitch('state',true);
除了修改属性的方法,bootstrapSwitch还提供了一些其他方法:
比如要实现按一个按钮可以切换switch可以这样写:
$('#mButton').click(function(){
$('#mySwitch input').bootstrapSwitch('toggleState');
})
最后讲一下点击switch时触发的事件。很简单,形式如下:
$('#mySwitch input').on('switchChange.bootstrapSwitch', function (event,state) {
alert(state);
});
本来以为这是个很简单的demo,不过没想到出现一个问题。状态为true时,点击switch左半边,程序运行正常,但点击右半边,弹出false后紧接着又弹出true,switch状态仍为true没有变。将alert()替换为console.log()或其它非阻塞语句,就不会出现这个问题了。具体原因有待进一步排查。