首页 > web前端 > js教程 > 正文

使用纯JavaScript动态添加Bootstrap Toggle开关

碧海醫心
发布: 2025-10-13 12:46:53
原创
225人浏览过

使用纯JavaScript动态添加Bootstrap Toggle开关

本教程详细介绍了如何利用纯javascript动态创建并初始化bootstrap toggle开关。文章将从引入必要库开始,逐步指导读者通过javascript创建`input`元素,设置其属性,将其添加到dom中,并最终使用jquery的`.bootstraptoggle()`方法将其转换为功能完备的开关,同时提供代码示例和注意事项,确保动态生成的开关能正常工作。

动态创建Bootstrap Toggle开关:纯JavaScript实现指南

在现代Web应用开发中,经常需要根据用户交互或后端数据动态生成UI组件。Bootstrap Toggle是一款流行的插件,能将标准的HTML复选框(checkbox)转换为美观且功能丰富的开关按钮。本教程将深入探讨如何仅使用纯JavaScript(结合jQuery进行插件初始化)来动态创建和激活这些Bootstrap Toggle开关。

1. 准备工作:引入必要的库

要使用Bootstrap Toggle,您需要引入Bootstrap CSS、Bootstrap Toggle CSS、jQuery以及Bootstrap JS和Bootstrap Toggle JS。确保这些库的引入顺序正确,通常jQuery应在Bootstrap JS之前,而Bootstrap Toggle JS应在Bootstrap JS之后。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态添加Bootstrap Toggle开关</title>
    <!-- 引入 Bootstrap 4.x CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <!-- 引入 Bootstrap Toggle CSS -->
    <link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
</head>
<body>
    <div class="container mt-5">
        <h1>动态添加Bootstrap Toggle开关示例</h1>
        <div id="switch-host" class="mb-3 border p-3">
            <!-- 动态添加的开关将显示在这里 -->
            <p>点击下方按钮添加开关:</p>
        </div>
        <button class="btn btn-primary mr-2" onclick="addBasicSwitch('switch-host')">添加基本开关</button>
        <button class="btn btn-success" onclick="addCustomSwitch('switch-host', 'success', 'danger', '启用', '禁用', true)">添加自定义开关</button>
    </div>

    <!-- 引入 jQuery (Bootstrap Toggle 依赖 jQuery) -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <!-- 引入 Bootstrap 4.x JS (Bootstrap Toggle 依赖 Bootstrap JS) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
    <!-- 引入 Bootstrap Toggle JS -->
    <script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>

    <script>
        // JavaScript代码将在此处添加
    </script>
</body>
</html>
登录后复制

2. 理解Bootstrap Toggle的工作原理

Bootstrap Toggle通过将一个普通的<input type="checkbox">元素转换为一个带有自定义样式和交互的开关。对于静态HTML,只需在input元素上添加data-toggle="toggle"属性即可。然而,当通过JavaScript动态创建元素时,仅添加此属性是不够的;我们还需要在元素被添加到DOM后,手动调用jQuery的.bootstrapToggle()方法来初始化它。

3. 核心实现:动态创建与初始化开关

以下是实现动态添加Bootstrap Toggle开关的JavaScript函数。我们将创建两个函数:一个用于添加基本开关,另一个用于添加带自定义样式的开关。

立即学习Java免费学习笔记(深入)”;

度加剪辑
度加剪辑

度加剪辑(原度咔剪辑),百度旗下AI创作工具

度加剪辑 63
查看详情 度加剪辑

3.1 创建基本开关的函数

这个函数将创建一个标准的复选框,并将其转换为Bootstrap Toggle开关。

        let switchCounter = 0; // 用于为每个动态创建的开关生成唯一ID

        /**
         * 动态添加一个基本的 Bootstrap Toggle 开关到指定的宿主元素。
         * @param {string} hostElId - 宿主元素的ID,开关将被添加到此元素内。
         */
        function addBasicSwitch(hostElId) {
            const host = document.getElementById(hostElId);
            if (!host) {
                console.error(`宿主元素ID为 "${hostElId}" 未找到。`);
                return;
            }

            const uniqueId = `dynamicSwitch${++switchCounter}`;

            // 1. 创建 input 元素
            const inputEl = document.createElement("input");
            inputEl.setAttribute("type", "checkbox");
            inputEl.setAttribute("id", uniqueId); // 为开关设置唯一ID
            inputEl.setAttribute("checked", false); // 默认不选中
            // inputEl.dataset.toggle = "toggle"; // 对于动态添加,通常通过JS初始化,此属性可省略但无害

            // 2. 将 input 元素添加到 DOM
            // 为了更好的布局,我们可以在外面包一个div
            const switchWrapper = document.createElement("div");
            switchWrapper.className = "form-group"; // 添加一些间距
            const labelEl = document.createElement("label");
            labelEl.setAttribute("for", uniqueId);
            labelEl.textContent = `开关 ${switchCounter}: `;
            switchWrapper.appendChild(labelEl);
            switchWrapper.appendChild(inputEl);
            host.appendChild(switchWrapper);

            // 3. 使用 jQuery 初始化 Bootstrap Toggle
            // 这一步是关键!它将普通的checkbox转换为Bootstrap Toggle样式。
            $(`#${uniqueId}`).bootstrapToggle();
            console.log(`已添加并初始化基本开关: ${uniqueId}`);
        }
登录后复制

3.2 创建带自定义样式开关的函数

除了基本功能,Bootstrap Toggle还支持通过data-*属性进行丰富的自定义,例如开关的颜色、文本、大小等。这个函数将演示如何动态设置这些属性。

        /**
         * 动态添加一个带自定义样式的 Bootstrap Toggle 开关。
         * @param {string} hostElId - 宿主元素的ID。
         * @param {string} onStyle - 开启时的样式(如 'success', 'primary')。
         * @param {string} offStyle - 关闭时的样式(如 'danger', 'secondary')。
         * @param {string} onText - 开启时显示的文本。
         * @param {string} offText - 关闭时显示的文本。
         * @param {boolean} initialState - 开关的初始状态(true为选中,false为未选中)。
         */
        function addCustomSwitch(hostElId, onStyle, offStyle, onText, offText, initialState) {
            const host = document.getElementById(hostElId);
            if (!host) {
                console.error(`宿主元素ID为 "${hostElId}" 未找到。`);
                return;
            }

            const uniqueId = `dynamicSwitch${++switchCounter}`;

            const inputEl = document.createElement("input");
            inputEl.setAttribute("type", "checkbox");
            inputEl.setAttribute("id", uniqueId);
            inputEl.setAttribute("checked", initialState ? "checked" : false); // 设置初始选中状态

            // 设置自定义 data-* 属性
            inputEl.dataset.onstyle = onStyle;
            inputEl.dataset.offstyle = offStyle;
            inputEl.dataset.on = onText;
            inputEl.dataset.off = offText;
            inputEl.dataset.size = "small"; // 示例:设置大小为 'small'

            // 将 input 元素添加到 DOM
            const switchWrapper = document.createElement("div");
            switchWrapper.className = "form-group";
            const labelEl = document.createElement("label");
            labelEl.setAttribute("for", uniqueId);
            labelEl.textContent = `自定义开关 ${switchCounter}: `;
            switchWrapper.appendChild(labelEl);
            switchWrapper.appendChild(inputEl);
            host.appendChild(switchWrapper);

            // 初始化 Bootstrap Toggle
            $(`#${uniqueId}`).bootstrapToggle();
            console.log(`已添加并初始化自定义开关: ${uniqueId}`);
        }
登录后复制

4. 完整代码示例

将上述JavaScript函数放置在HTML文件中的<script>标签内,即可实现动态添加Bootstrap Toggle开关。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态添加Bootstrap Toggle开关</title>
    <!-- 引入 Bootstrap 4.x CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css" integrity="sha384-xOolHFLEh07PJGoPkLv1IbcEPTNtaed2xpHsD9ESMhqIYd0nLMwNLD69Npy4HI+N" crossorigin="anonymous">
    <!-- 引入 Bootstrap Toggle CSS -->
    <link href="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/css/bootstrap4-toggle.min.css" rel="stylesheet">
    <style>
        /* 示例样式,使开关之间有更好的视觉间隔 */
        .form-group {
            margin-bottom: 1rem;
        }
        .form-group label {
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <h1>动态添加Bootstrap Toggle开关示例</h1>
        <div id="switch-host" class="mb-3 border p-3 rounded">
            <!-- 动态添加的开关将显示在这里 -->
            <p>点击下方按钮添加开关:</p>
        </div>
        <button class="btn btn-primary mr-2" onclick="addBasicSwitch('switch-host')">添加基本开关</button>
        <button class="btn btn-success" onclick="addCustomSwitch('switch-host', 'success', 'danger', '启用', '禁用', true)">添加自定义开关</button>
    </div>

    <!-- 引入 jQuery (Bootstrap Toggle 依赖 jQuery) -->
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <!-- 引入 Bootstrap 4.x JS (Bootstrap Toggle 依赖 Bootstrap JS) -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-Fy6S3B9q64WdZWQUiU+q4/2Lc9npb8tCaSX9FK7E8HnRr0Jz8D6OP9dO5Vg3Q9ct" crossorigin="anonymous"></script>
    <!-- 引入 Bootstrap Toggle JS -->
    <script src="https://cdn.jsdelivr.net/gh/gitbrent/bootstrap4-toggle@3.6.1/js/bootstrap4-toggle.min.js"></script>

    <script>
        let switchCounter = 0; // 用于为每个动态创建的开关生成唯一ID

        /**
         * 动态添加一个基本的 Bootstrap Toggle 开关到指定的宿主元素。
         * @param {string} hostElId - 宿主元素的ID,开关将被添加到此元素内。
         */
        function addBasicSwitch(hostElId) {
            const host = document.getElementById(hostElId);
            if (!host) {
                console.error(`宿主元素ID为 "${hostElId}" 未找到。`);
                return;
            }

            const uniqueId = `dynamicSwitch${++switchCounter}`;

            // 1. 创建 input 元素
            const inputEl = document.createElement("input");
            inputEl.setAttribute("type", "checkbox");
            inputEl.setAttribute("id", uniqueId); // 为开关设置唯一ID
            inputEl.setAttribute("checked", false); // 默认不选中

            // 2. 将 input 元素添加到 DOM
            const switchWrapper = document.createElement("div");
            switchWrapper.className = "form-group d-flex align-items-center"; // 使用flexbox对齐label和开关
            const labelEl = document.createElement("label");
            labelEl.setAttribute("for", uniqueId);
            labelEl.textContent = `开关 ${switchCounter}: `;
            switchWrapper.appendChild(labelEl);
            switchWrapper.appendChild(inputEl);
            host.appendChild(switchWrapper);

            // 3. 使用 jQuery 初始化 Bootstrap Toggle
            // 这一步是关键!它将普通的checkbox转换为Bootstrap Toggle样式。
            $(`#${uniqueId}`).bootstrapToggle();
            console.log(`已添加并初始化基本开关: ${uniqueId}`);
        }

        /**
         * 动态添加一个带自定义样式的 Bootstrap Toggle 开关。
         * @param {string} hostElId - 宿主元素的ID。
         * @param {string} onStyle - 开启时的样式(如 'success', 'primary')。
         * @param {string} offStyle - 关闭时的样式(如 'danger', 'secondary')。
         * @param {string} onText - 开启时显示的文本。
         * @param {string} offText - 关闭时显示的文本。
         * @param {boolean} initialState - 开关的初始状态(true为选中,false为未选中)。
         */
        function addCustomSwitch(hostElId, onStyle, offStyle, onText, offText, initialState) {
            const host = document.getElementById(hostElId);
            if (!host) {
                console.error(`宿主元素ID为 "${hostElId}" 未找到。`);
                return;
            }

            const uniqueId = `dynamicSwitch${++switchCounter}`;

            const inputEl = document.createElement("input");
            inputEl.setAttribute("type", "checkbox");
            inputEl.setAttribute("id", uniqueId);
            inputEl.setAttribute("checked", initialState ? "checked" : false); // 设置初始选中状态

            // 设置自定义 data-* 属性
            inputEl.dataset.onstyle = onStyle;
            inputEl.
登录后复制

以上就是使用纯JavaScript动态添加Bootstrap Toggle开关的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号