Tailwind CSS:在没有 Javascript 的情况下创建切换开关

这篇实用文章向您展示了如何使用 Tailwind CSS 创建切换开关。不需要 Javascript 或任何其他库。

示例预览

我们将实现 2 个拨动开关。第一个是矩形,第二个是圆形。当开关关闭时,其背景为浅灰色。为 1 时,背景为蓝色。

以下是它们的实际工作方式:

Tailwind CSS:在没有 Javascript 的情况下创建切换开关

编码

这是生成您在演示中看到的网页的完整源代码:

<!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://cdn.tailwindcss.com"></script>
    <title>KindaCode.com</title>
</head>

<body class="p-20">
    <h1 class="text-4xl">KindaCode.com</h1>
    <h3 class="mb-10 text-xl">Use Tailwind CSS to Create Toggle Switches</h3>

    <!-- Rectangular switch -->
    <div>
        <label class="relative inline-block w-16 h-9">
            <input type="checkbox" class="peer opacity-0 w-0 h-0">
            <span class="absolute cursor-pointer top-0 left-0 right-0 bottom-0 bg-gray-300 duration-300 before:content-[''] before:absolute before:w-7 before:h-7 before:bottom-1 before:left-1
                before:bg-white before:duration-300 peer-checked:before:translate-x-7 peer-checked:bg-blue-500"></span>
        </label>
    </div>

    <!-- Rounded switch -->
    <div class="mt-5">
        <label class="relative inline-block w-16 h-9 rounded-full">
            <input type="checkbox" class="peer opacity-0 w-0 h-0">
            <span class="absolute cursor-pointer top-0 left-0 right-0 bottom-0 bg-gray-300 rounded-full duration-300 before:content-[''] before:absolute before:w-7 before:h-7 before:bottom-1 before:left-1 before:rounded-full
                before:bg-white before:duration-300 peer-checked:before:translate-x-7 peer-checked:bg-blue-500"></span>
        </label>
    </div>

</body>

</html>

解释

创建切换开关的要点是一个标签元素和一个不可见的复选框,该复选框具有零宽度 ( w-0 )、零高度 ( h-0 ) 和零不透明度(感谢opacity-0实用程序类)。

如果未选中该复选框,则表示切换开关已关闭。反之亦然,当复选框被选中时,切换开关的状态为on

我们使用span元素创建轨道。我们使用before伪元素创建拇指(白色控制器)。要根据复选框的状态更改span元素的背景颜色,我们将 peer 类添加到复选框,并将peer-checked修饰符与bg-blue-500实用程序一起用于span

结论

您已经了解了如何仅使用 Tailwind CSS 创建切换开关。您需要编写的代码不会太长,底层逻辑也不会太复杂。您可以修改代码、调整一些值、添加一些内容和删除一些内容,以使结果符合您的需求。