在項目中有個地方要用到一個開關,就找了一下發現boostrap-switch這個插件比較符合要求,網上查了不少資料也踩了不少坑。
因為主要就用到標題中兩個功能,所以就在這里介紹一下
以下是一個簡單的demo。其中js,css都是在線引入復制即可用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="http://cdn.static.runoob.com/libs/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://cdn.bootcss.com/bootstrap-switch/3.3.4/css/bootstrap3/bootstrap-switch.css" rel="stylesheet">
<style>
.center{
text-align: center;
margin-top: 100px;
}
#state{
font-size: 20px;
color: black;
font-family: "Adobe 黑體 Std R";
font-weight: bold;
}
.btn{
width: 60px;
}
</style>
</head>
<body>
<div class="center">
<input type="checkbox" name="switch">
<p id="state"></p><br>
<button type="button" class="btn btn-primary" id="on">on</button>
<button type="button" class="btn btn-warning" id="off">off</button>
</div>
</body>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script src="https://cdn.bootcss.com/bootstrap-switch/3.3.4/js/bootstrap-switch.js"></script>
<script>
$("input[name='switch']").bootstrapSwitch({
onText: "開啟",
offText: "關閉",
onSwitchChange: function (event, state) {
//監聽switch change事件,可以根據狀態把相應的業務邏輯代碼寫在這里
if (state == true) {
$("#state").html('switch turn no')
} else {
$("#state").html('switch turn off')
}
}
})
//兩個按鈕點擊動態切換bootsrap開關狀態
$("#on").click(function(e){
$("input[name='switch']").bootstrapSwitch("state",true);
})
$("#off").click(function(e){
$("input[name='switch']").bootstrapSwitch("state",false);
})
</script>
</html>

