TailwindCSS - 选中单选按钮时更改标签

TailwindCSS - Change Label When Radio Button Checked

我看到可以启用 TailwindCSS checked: 变体以在选中时更改输入元素,但是如何在选中时更改输入的标签?

这是相关的 Tailwind CSS docs.

示例代码如下。

启用 tailwind.config.js 中的变体后,将 checked:bg-green-300 放入 div 或标签不起作用。它仅在输入中有效。

<div>
  <label>
    <input checked type="radio" name="option1" id="option1" className="hidden" />
    <div>option1</div>
  </label>
  <label>
    <input checked type="radio" name="option2" id="option1" className="hidden" />
    <div>option2</div>
  </label>
</div>

编辑: 作为 版本 2.2+ 的发布,它内置了对名为 peer 的兄弟选择器变体的支持(观看更新 release)

This feature is only available in Just-in-Time mode.

<label>
    <input checked type="radio" name="option" id="option1" class="hidden peer" />
    <div class="peer-checked:bg-red-600">option1</div>
</label>

对于 2.2 以下的版本: 您需要编写自己的插件来添加新变体。更多信息 here

例如命名为label-checked

tailwind.config.js

const plugin = require('tailwindcss/plugin');

module.exports = {
    purge: [],
    darkMode: false, // or 'media' or 'class'
    theme: {},
    variants: {
        extend: {
            backgroundColor: ['label-checked'], // you need add new variant to a property you want to extend
        },
    },
    plugins: [
        plugin(({ addVariant, e }) => {
            addVariant('label-checked', ({ modifySelectors, separator }) => {
                modifySelectors(
                    ({ className }) => {
                        const eClassName = e(`label-checked${separator}${className}`); // escape class
                        const yourSelector = 'input[type="radio"]'; // your input selector. Could be any
                        return `${yourSelector}:checked ~ .${eClassName}`; // ~ - CSS selector for siblings
                    }
                )
            })
        }),
    ],
};

此配置适用于下一种情况(我们扩展了 backgroundColor,因此它应该适用于 bg-color 类):

1 - 标签是包装器,它的文本应该包装在任何选择器中(在本例中 div)

<label>
    <input checked type="radio" name="option1" id="option1" class="hidden" />
    <div class="label-checked:bg-red-600">option1</div>
</label>

2 - 标签 after input

<input checked type="radio" name="option1" id="option1" class="hidden" />
<label for="option-1" class="label-checked:bg-red-600"></label>

演示版 - https://play.tailwindcss.com/SEQ4NRpPV3

根据 tailwind 2.2.0

使用对等 class
<input type="checkbox" name="themeToggler" id="themeToggler" class="peer" />
<label for="themeToggler" class="w-10 h-10 bg-gray-400 peer-checked:bg-red-400"></label>

DEMO

Tailwind 的同行 class 是解决此问题的现代方法。

您可以通过向 HTML 添加两个 class 来添加对等行为。

  1. 将对等点 class 添加到要观察其状态的 HTML 标签。
  2. 将经过同行检查的 class 添加到同级元素中,然后添加所需的行为更改。

查看详细示例here