【问题标题】:tailwind css change color of button on focus顺风css改变焦点按钮的颜色
【发布时间】:2021-12-23 16:32:19
【问题描述】:

我有两个按钮,蓝色和红色。

我想设置当红色按钮被点击/聚焦蓝色按钮也应该变成红色。

如何使用tailwind css实现它。

<link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet"/>

<button class="focus:bg-red-700 bg-red-400 font-bold px-4 py-4 rounded-lg">
RED
</button>

<button class=" bg-blue-400 font-bold px-4 py-4 rounded-lg">
BLUE
</button>

【问题讨论】:

    标签: html css tailwind-css


    【解决方案1】:

    Tailwind 没有 combinators 的 CSS。猜猜,你有两种方法可以实现这一点。

    1. 创建一个额外的 css 文件并添加这一行
    button.bg-red-400:focus ~ button.bg-blue-400 {
      background-color: rgba(185, 28, 28, 1);
    }
    

    button.bg-red-400:focus~button.bg-blue-400 {
      background-color: rgba(185, 28, 28, 1);
    }
    <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" />
    
    <button class="focus:bg-red-700 bg-red-400 font-bold px-4 py-4 rounded-lg">RED</button>
    
    <button class="bg-blue-400 font-bold px-4 py-4 rounded-lg">BLUE</button>
    1. 您可以使用 @Variants documentation 创建自己的自定义类,但不能使用 CDN 中的链接。

    在使用 CDN 构建之前,请注意,如果不将 Tailwind 整合到您的构建过程中,许多使 Tailwind CSS 变得出色的功能将无法使用。 documentation

    1. javascript 解决方案

      // Select all elements with `bg-blue-400` class
      const blueBox = document.querySelectorAll('.bg-blue-400');
    
      const changeColor = ev => {
        // Define button in the DOM
        const button = ev.target.closest('button');
        // Check, if the button was clicked
        if (button) {
          // Chenge color in the DIVs
          for (const box of blueBox) {
            box.classList.add('bg-red-400');
            box.classList.remove('bg-blue-400');
          }
          return;
        }
        // If clicked outside, the color will switch back
        for (const box of blueBox) {
          box.classList.add('bg-blue-400');
          box.classList.remove('bg-red-400');
        }
      };
      document.addEventListener('click', changeColor);
    <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" />
    
    <div>
      <button class="one bg-red-400 font-bold px-4 py-4 rounded-lg">RED</button>
      <div class="bg-blue-400 font-bold px-4 py-4 rounded-lg">BLUE</div>
    </div>
    
    <div class="two bg-blue-400 font-bold px-4 py-4 rounded-lg">APPLY COLOR HERE</div>

    【讨论】:

    猜你喜欢
    • 2017-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 2014-04-16
    • 1970-01-01
    相关资源
    最近更新 更多