Javascript 如何在 Bootstrap 中创建切换按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13511368/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a toggle button in Bootstrap
提问by Megan Sime
I originally created a web app in HTML, CSS and JavaScript, then was asked to create it again in Bootstrap too. I've done it all fine, but I had toggle buttons in the web app that have changed back to radio (originally checkbox) buttons instead of the toggle buttons I had originally.
我最初用 HTML、CSS 和 JavaScript 创建了一个 Web 应用程序,然后也被要求在 Bootstrap 中再次创建它。我一切都做得很好,但是我在 Web 应用程序中有切换按钮,它们已变回单选按钮(最初是复选框)按钮,而不是我最初拥有的切换按钮。
The code for the buttons is:
按钮的代码是:
<label>
Notifications
<span class='toggle'>
<input type='radio'
class='notifications'
name='notifications'
id='notifications' />
</span>
</li>
<label>
Preview
<span class='toggle'>
<input type='radio'
class='preview'
name='preview'
id='preview' />
</span>
</li>
and the JavaScript and CSS files that the HTML page is linked to are:
HTML 页面链接到的 JavaScript 和 CSS 文件是:
<script src = 'jqtouch.js'></script>
<script src="jquery.js"></script>
<script src="js/bootstrap.js"></script>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">
Is there a way to change the code so I can get the toggle button back?
有没有办法更改代码,以便我可以恢复切换按钮?
采纳答案by smonff
Initial answer from 2013
2013 年的初步回答
An excellent (unofficial) Bootstrap Switch is available.
一个优秀的(非官方的)Bootstrap Switch 可用。
<input type="checkbox" name="my-checkbox" checked>
$("[name='my-checkbox']").bootstrapSwitch();
It uses radio types orcheckboxes as switches. A typeattribute has been added since V.1.8.
它使用无线电类型或复选框作为开关。type从 V.1.8 开始添加了一个属性。
Source code is available on Github.
源代码可在 Github 上获得。
Note from 2018
2018 年的笔记
I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issuesas pointed by many people.
我现在不建议使用那些旧的 Switch 按钮,因为它们似乎总是受到许多人指出的可用性问题的困扰。
Please consider having a look at modern Switches like this onefrom the React Component framework(not Bootstrap related, but can be integrated in Bootstrap grid and UI though).
请考虑从React Component 框架中查看类似这样的现代 Switch(与 Bootstrap 无关,但可以集成到 Bootstrap 网格和 UI 中)。
Other implementations exist for Angular, View or jQuery.
Angular、View 或 jQuery 存在其他实现。
import '../assets/index.less'
import React from 'react'
import ReactDOM from 'react-dom'
import Switch from 'rc-switch'
class Switcher extends React.Component {
state = {
disabled: false,
}
toggle = () => {
this.setState({
disabled: !this.state.disabled,
})
}
render() {
return (
<div style={{ margin: 20 }}>
<Switch
disabled={this.state.disabled}
checkedChildren={'开'}
unCheckedChildren={'关'}
/>
</div>
</div>
)
}
}
ReactDOM.render(<Switcher />, document.getElementById('__react-content'))
回答by Sam
If you don't mind changing your HTML, you can use the data-toggleattribute on <button>s. See the Single togglesection of the button examples:
如果您不介意更改 HTML,则可以使用sdata-toggle上<button>的属性。请参阅按钮示例的单切换部分:
<button type="button" class="btn btn-primary" data-toggle="button">
Single toggle
</button>
回答by StriplingWarrior
Bootstrap 3 has options to create toggle buttons based on checkboxes or radio buttons: http://getbootstrap.com/javascript/#buttons
Bootstrap 3 具有基于复选框或单选按钮创建切换按钮的选项:http: //getbootstrap.com/javascript/#buttons
Checkboxes
复选框
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="checkbox" checked> Option 1 (pre-checked)
</label>
<label class="btn btn-primary">
<input type="checkbox"> Option 2
</label>
<label class="btn btn-primary">
<input type="checkbox"> Option 3
</label>
</div>
Radio buttons
单选按钮
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="option1" checked> Option 1 (preselected)
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option2"> Option 2
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="option3"> Option 3
</label>
</div>
For these to work you must initialize .btns with Bootstrap's Javascript:
要使这些工作,您必须.btn使用 Bootstrap 的 Javascript初始化s:
$('.btn').button();
回答by p2kmgcl
I've been trying to activate 'active' class manually with javascript. It's not as usable as a complete library, but for easy cases seems to be enough:
我一直在尝试使用 javascript 手动激活“活动”类。它不像一个完整的库那样可用,但对于简单的情况似乎就足够了:
var button = $('#myToggleButton');
button.on('click', function () {
$(this).toggleClass('active');
});
If you think carefully, 'active' class is used by bootstrap when the button is being pressed, not before or after that (our case), so there's no conflict in reuse the same class.
如果你仔细想想,'active' 类是在按钮被按下时被引导程序使用的,而不是在按钮被按下之前或之后(我们的例子),所以重用同一个类没有冲突。
Try this example and tell me if it fails: http://jsbin.com/oYoSALI/1/edit?html,js,output
试试这个例子并告诉我它是否失败:http: //jsbin.com/oYoSALI/1/edit?html,js,output
回答by Rick
If you want to keep a small code base, and you are only going to be needing the toggle button for a small part of the application. I would suggest instead maintain you're javascript code your self (angularjs, javascript, jquery) and just use plain CSS.
如果您想保留一个小的代码库,并且您只需要应用程序的一小部分的切换按钮。我建议改为保持你自己的 javascript 代码(angularjs、javascript、jquery)并且只使用普通的 CSS。
Good toggle button generator: https://proto.io/freebies/onoff/
好的切换按钮生成器:https: //proto.io/freebies/onoff/
回答by Muhammet Can TONBUL
Here this very usefull For Bootstrap Toggle Button. Example in code snippet!! and jsfiddle below.
这对于 Bootstrap Toggle Button非常有用。代码片段中的示例!!和下面的jsfiddle。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<input id="toggle-trigger" type="checkbox" checked data-toggle="toggle">
<button class="btn btn-success" onclick="toggleOn()">On by API</button>
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>
<button class="btn btn-primary" onclick="getValue()">Get Value</button>
<script>
//If you want to change it dynamically
function toggleOn() {
$('#toggle-trigger').bootstrapToggle('on')
}
function toggleOff() {
$('#toggle-trigger').bootstrapToggle('off')
}
//if you want get value
function getValue()
{
var value=$('#toggle-trigger').bootstrapToggle().prop('checked');
console.log(value);
}
</script>
Update 2020 For Bootstrap 4
Bootstrap 4 的 2020 年更新
I recommended bootstrap4-togglein 2020.
我在 2020 年推荐了bootstrap4-toggle。
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<link href="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/css/bootstrap4-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/js/bootstrap4-toggle.min.js"></script>
<input id="toggle-trigger" type="checkbox" checked data-toggle="toggle" data-onstyle="success">
<button class="btn btn-success" onclick="toggleOn()">On by API</button>
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>
<button class="btn btn-primary" onclick="getValue()">Get Value</button>
<script>
//If you want to change it dynamically
function toggleOn() {
$('#toggle-trigger').bootstrapToggle('on')
}
function toggleOff() {
$('#toggle-trigger').bootstrapToggle('off')
}
//if you want get value
function getValue()
{
var value=$('#toggle-trigger').bootstrapToggle().prop('checked');
console.log(value);
}
</script>
回答by OMA
You can use the CSS Toggle Switch library. Just include the CSS and program the JS yourself: http://ghinda.net/css-toggle-switch/bootstrap.html
您可以使用 CSS Toggle Switch 库。只需包含 CSS 并自己编写JS:http: //ghinda.net/css-toggle-switch/bootstrap.html
回答by Ivan Rodriguez
You can use the Material Design Switch for Bootstrap 3.3.0
您可以使用 Bootstrap 3.3.0 的 Material Design Switch
http://bootsnipp.com/snippets/featured/material-design-switch
http://bootsnipp.com/snippets/featured/material-design-switch
回答by ohkts11
Bootstrap 4 solution
Bootstrap 4 解决方案
bootstrap 4 ships built-in toggle. Here is the documentation. https://getbootstrap.com/docs/4.3/components/forms/#switches
bootstrap 4 内置切换。这是文档。 https://getbootstrap.com/docs/4.3/components/forms/#switches
回答by Erik Vullings
In case someone is still looking for a nice switch/toggle button, I followed Rick's suggestion and created a simple angular directive around it, angular-switch. Besides preferring a Windows styled switch, the total download is also much smaller (2kb vs 23kb minified css+js) compared to angular-bootstrap-switch and bootstrap-switch mentioned above together.
如果有人仍在寻找一个不错的开关/切换按钮,我遵循 Rick 的建议并围绕它创建了一个简单的角度指令angular-switch。除了更喜欢 Windows 风格的开关之外,与上面提到的 angular-bootstrap-switch 和 bootstrap-switch 相比,总下载量也小得多(2kb vs 23kb 缩小的 css+js)。
You would use it as follows. First include the required js and css file:
您将按如下方式使用它。首先包含所需的js和css文件:
<script src="./bower_components/angular-switch/dist/switch.js"></script>
<link rel="stylesheet" href="./bower_components/angular-switch/dist/switch.css"></link>
And enable it in your angular app:
并在您的 angular 应用程序中启用它:
angular.module('yourModule', ['csComp'
// other dependencies
]);
Now you are ready to use it as follows:
现在您可以按如下方式使用它:
<switch state="vm.isSelected"
textlabel="Switch"
changed="vm.changed()"
isdisabled="{{isDisabled}}">
</switch>


