简体   繁体   English

应用不透明度而不影响子元素

[英]Apply opacity without effecting the child elements

I have a div that has a background image, and when It got hovered, the div will be given opacity 0.7 我有一个具有背景图像的div ,当它悬停时,该div将被赋予不透明度0.7

<div>
  <span>text</span>
</div>

Secondly I've a span that when I got hovered, I use show() to overwrite its default css display:none . 其次,我有一个跨度,当我将鼠标悬停时,我使用show()覆盖其默认的CSS display:none

The problem is the opacity applies to the span as well, so the text doesn't stand out as I expect. 问题是不透明度也适用于span ,因此文本不像我期望的那样突出。 I tried to set span to opacity 1 on the hover event, no luck with that. 我试图在悬停事件上将span设置为不透明度1,这很不走运。

The opacity will affect all children of an element. 不透明度将影响元素的所有子元素。 You can achieve what you want by using two parallel divs, one for the background image with opacity and the other with the span and the rest of the content . 您可以通过使用两个平行的div来实现所需的效果,一个div用于不透明的背景图像,另一个用于span和content的其余部分。 The absolute positioning of bg-img will not affect the position of content and will appear behind this. bg-imgabsolute位置不会影响content的位置,并且会显示在此后面。 You also want to adjust the positioning and size of bg-img using top , bottom , right , left , width or height 您还想使用topbottomrightleftwidthheight调整bg-img的位置和大小

HTML : HTML

<div>
    <div class="bg-img"></div>
    <div class="content">
        <span>text</span>
    </div>
</div>

CSS : CSS

.bg-img {
    position: absolute;
}
.bg-img:hover {
    opacity: 0.7;
}

If the background color behind the image is known, you can apply an opaque background color to the <span> to make the background image look faded. 如果已知图像后面的背景色,则可以将不透明的背景色应用于<span>以使背景图像看起来褪色。

http://jsfiddle.net/TxQny/ http://jsfiddle.net/TxQny/

HTML: HTML:

<div class="bg">
    <span class="overlay">text</span>
</div>

CSS: CSS:

.bg {
    background-color: #e0e0e0; /* You can use an image instead */
}
.overlay {
    display: block;
}
.overlay:hover {
    background-color: rgba(0, 255, 255, 0.3);
}

Of course, this assumes that all the browsers you care about supporting support RGBA. 当然,这是假设您关心的所有浏览器都支持RGBA。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM