bootstrap-switch,切换触发事件及动态切换
在项目中有个地方要用到一个开关,就找了一下发现boostrap-switch这个插件比较符合要求,网上查了不少资料也踩了不少坑。
因为主要就用到标题中两个功能,所以就在这里介绍一下
以下是一个简单的demo。其中js,css都是在线引入复制即可用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <! 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 > |
标签:
Javascript
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性