本文介绍了更改背景颜色不透明度而不更改背景图像不透明度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户将鼠标悬停时,我想增加按钮的背景色亮度.但无论按钮的颜色如何,我都想这样做.在下面,您可以看到四个按钮.只有最后一个有效,因为它已为黄色显式配置了:hover处理程序.

I want to increase button's background color brightness when user hovers it. But I wanna do that irrespective of the color a button has. Bellow, you can see four buttons. Only the last one works, because it has :hover handler explicitly configured for yellow color.

.hoverme {
    display: inline-block;
    padding:0px;
    width:5em;
    height:5em;
    background-color:black;
    cursor: pointer;
}
.hoverme:hover .inner {
    /*
   Pseudocode:
     background-color-opacity: 1;
    */
}
.hoverme .inner {
    margin: 0px;
    padding:0px;
    height: 100%;
}

.hoverme.red .inner {
    background-color: rgba(255,0,0,.9);
}
.hoverme.green .inner {
    background-color: rgba(0,200,0,.9);
}
.hoverme.yellow .inner {
    background-color: rgba(250,240,0,.9);
}

.hoverme.yellow.works-but-not-nice:hover .inner {
    background-color: rgba(250,240,0,1);
}
<div class="hoverme red"><div class="inner">text</div></div>

<div class="hoverme green"><div class="inner">text</div></div>

<div class="hoverme yellow"><div class="inner">text</div></div>

<div class="hoverme yellow works-but-not-nice"><div class="inner">this works</div></div>

因此,我想更改背景颜色的不透明度,无论它是黄色,红色还是其他颜色.背景图片或内容应始终完全不透明.

So I'd like to change the opacity of background color regardless of whether it's yellow, red or whatever. Background images or content should always be fully opaque.

这样做的好处是无需添加更多div元素.

Bonus points for doing this without adding more div elements.

推荐答案

在这种情况下,我将考虑在定义悬停时更改的不透明度值的地方使用CSS变量:

In this case I would consider the use of CSS variable on where I define the value of opacity that I change on hover:

:root {
  --opacity:0.8;
}
.hoverme {
    display: inline-block;
    padding:0px;
    width:5em;
    height:5em;
    background-color:black;
    cursor: pointer;
}
.hoverme:hover .inner {
   --opacity:1;
}
.hoverme .inner {
    margin: 0px;
    padding:0px;
    height: 100%;
}

.hoverme.red .inner {
    background-color: rgba(255,0,0,var(--opacity));
}
.hoverme.green .inner {
    background-color: rgba(0,200,0,var(--opacity));
}
.hoverme.yellow .inner {
    background-color: rgba(250,240,0,var(--opacity));
}
<div class="hoverme red"><div class="inner">text</div></div>

<div class="hoverme green"><div class="inner">text</div></div>

<div class="hoverme yellow"><div class="inner">text</div></div>

这篇关于更改背景颜色不透明度而不更改背景图像不透明度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-20 04:59