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

won*_*ngz 5 radio-button tailwind-css

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

这是相关的 Tailwind CSS文档

下面的示例代码。

在 中启用变体后tailwind.config.js,放入checked:bg-green-300div 或标签不起作用。它只适用于输入。

<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>
Run Code Online (Sandbox Code Playgroud)

Iha*_*nka 12

编辑:随着2.2+ 版本的发布,它内置了对兄弟选择器变体的支持,称为peer(手表更新发布

此功能仅在即时模式下可用。

<label>
    <input checked type="radio" name="option" id="option1" class="hidden peer" />
    <div class="peer-checked:bg-red-600">option1</div>
</label>
Run Code Online (Sandbox Code Playgroud)

对于低于 2.2 的版本: 您需要编写自己的插件来添加新变体。更多信息在这里

例如,让它命名 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
                    }
                )
            })
        }),
    ],
};
Run Code Online (Sandbox Code Playgroud)

此配置应该适用于下一种情况(我们扩展了 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>
Run Code Online (Sandbox Code Playgroud)

2 -输入后的标签

<input checked type="radio" name="option1" id="option1" class="hidden" />
<label for="option-1" class="label-checked:bg-red-600"></label>
Run Code Online (Sandbox Code Playgroud)

演示- https://play.tai​​lwindcss.com/SEQ4NRpPV3