【问题标题】:Change color of button using css or tailwind使用 css 或 tailwind 更改按钮的颜色
【发布时间】:2021-12-23 18:37:57
【问题描述】:

我试图在单击主按钮时更改按钮的颜色,一种颜色正在改变为什么其他按钮颜色没有改变,是因为它在主<div> 之外我如何在不删除任何 div 的情况下实现它。

code

button.one:focus~div.two {
  background-color: rgba(185, 28, 28, 1);
}
<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">MAIN BUTTON</button>

<div class="two bg-blue-400 font-bold  px-4 py-4 rounded-lg">RED
</div>

</div>

<div class="two bg-blue-400 font-bold  px-4 py-4 rounded-lg">MAKE THIS RED TOO</div>

【问题讨论】:

    标签: html css tailwind-css


    【解决方案1】:

    编辑

    在 Chrome 中,button 正在获取点击,而父级 div 没有获得焦点。我对此做了一些调整,现在它在 Chrome 中可以正常工作了。

    1. 忽略通过pointer-events: none直接点击button
    2. 为了让事情有点容易理解,我补充说:
      • aria-hidden="true"button,这样屏幕阅读器就不会向用户大声朗读。
      • aria-label="MAIN BUTTON"role="button" to the parent div, so that screen readers can treat the div` 就像一个按钮。
      • cursor: pointer 给父 div,所以感觉就像一个按钮(从用户体验的角度来看)。

    唯一的纯CSS 方法是将tabindex="0" 添加到外部div,这让我们可以利用它的焦点和通用兄弟组合(~)来发挥我们的优势。我给了div 一个inline inline-block 显示,这样可点击区域就是其子内容的确切宽度。

    div[tabindex="0"] {
      display: inline-block;
      outline: none;
      cursor: pointer;
      z-index: 1;
    }
    
    div:focus .two,
    div:focus~.two {
      background-color: rgba(185, 28, 28, 1);
    }
    
    div[tabindex="0"] > button {
      pointer-events: none;
    }
    <link href="https://unpkg.com/tailwindcss@^2/dist/tailwind.min.css" rel="stylesheet" />
    
    
    <div tabindex="0" role="button" aria-label="MAIN BUTTON">
    
      <button aria-hidden="true" class="one bg-red-400 font-bold px-4 py-4 rounded-lg">MAIN BUTTON</button>
    
      <div class="two bg-blue-400 font-bold  px-4 py-4 rounded-lg">RED
      </div>
    
    </div>
    
    <div class="two bg-blue-400 font-bold  px-4 py-4 rounded-lg">MAKE THIS RED TOO</div>

    【讨论】:

    • 当我点击主按钮/第一个按钮时什么都没有改变?
    • @Fayakon 我为你更新了我的答案。抱歉这个问题。
    • 谢谢你,如果我在标签索引上方添加一个 div,你能告诉/解决为什么它不起作用吗? play.tailwindcss.com/PnAJCarYYz
    • @Fayakon 您的HTML 与您在问题中包含的内容不同。此外,您的CSS 完全在顺风沙箱中工作。看看这个:play.tailwindcss.com/H61nnozDBn
    • 它正在工作,但是当我在标签索引上方添加一个额外的 div 时为什么它停止工作?play.tailwindcss.com/PnAJCarYYz
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 2012-03-13
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-07-31
    • 1970-01-01
    相关资源
    最近更新 更多