您好,欢迎访问一九零五行业门户网

如何使用 JavaScript 添加引导切换开关?

bootstrap 库为用户提供了许多功能,使他们的编码体验更加流畅。用户可以选择的此类功能之一是切换开关。切换开关是其有用的功能之一,它使用户能够添加可以在打开和关闭等两种状态之间切换的组件。
引导切换开关级联样式表 (css) 框架 bootstrap 是一个工具包,它使创建网站变得更简单且更符合标准。它可以与 javascript 一起使用来创建响应式用户界面。简单的 bootstrap 切换开关组件用于选择两个可用替代方案之一。经常用作开/关开关。
方法我们将在本文中了解两种使用 javascript 添加引导切换开关的不同方法。它们如下 -
使用 bootstraptoogle() 方法
使用javascript方法toggleon()和toggleoff()
方法一:使用bootstraptoogle()方法切换 bootstrap 元素是使用内置的 data-toggle 属性完成的。在这种情况下,该任务是使用 bootstraptoggle() 方法执行的。可以使用 bootstraptoggle() 方法来切换开关。当用户在开关处于禁用状态时点击复选框时,它会切换到启用状态。 bootstraptoggle() 方法将复选框切换为禁用状态(如果当前已启用)。
示例以下是我们将在本示例中使用的完整代码 -
<!doctype html><html><head> <title>how to add bootstrap toggle-switch using javascript?</title> <script src=https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js></script> <link rel=stylesheet href=https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css> <script src=https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js></script> <link href=https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css rel=stylesheet></head><body> <h4>how to add bootstrap toggle-switch using javascript?</h4> <div class=container mt-5> <input type=checkbox id=toggle-input> </div> <script> $(function () { $('#toggle-input').bootstraptoggle({ on: 'on', off: 'off' }); }) </script></body></html>
方法2:使用javascript方法toggleon()和toggleoff()还可以使用单独的按钮来翻转开关,单击这些按钮时,会执行 javascript 功能。根据开关之前的状态,我们可以使用 javascript 代码来打开或关闭开关。这里,toggleoff()方法关闭开关,而toggleon()方法打开开关。
示例以下是我们将在本示例中使用的完整代码 -
<!doctype html><html><head> <title>how to add bootstrap toggle-switch using javascript?</title> <link rel=stylesheet href=https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css <script src=https://code.jquery.com/jquery.min.js></script> <script src=https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js></script> <link href=https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css rel=stylesheet></head><body> <h4>how to add bootstrap toggle-switch using javascript?</h4> <div class=container mt-5> <input id=toggle-trigger type=checkbox data-toggle=toggle> <button class=btn btn-success onclick=toggleon()> on button </button> <button class=btn btn-danger onclick=toggleoff()> off button </button> </div> <script> function toggleon() { $('#toggle-trigger').bootstraptoggle('on') } function toggleoff() { $('#toggle-trigger').bootstraptoggle('off') } </script></body></html>
结论在本文中,我们了解了如何使用 javascript 添加引导切换开关。我们研究了两种完成此任务的方法。我们首先看到了如何使用 bootstraptoggle() 方法来做到这一点,后来我们还看到了如何使用toggleon() 和toggleoff() 方法来获得相同的效果。
以上就是如何使用 javascript 添加引导切换开关?的详细内容。
其它类似信息

推荐信息