This question already has answers here:
I do not want to inherit the child opacity from the parent in CSS
                                
                                    (14个回答)
                                
                        
                        
                            Can I set an opacity only to the background image of a div?
                                
                                    (8个答案)
                                
                        
                                7个月前关闭。
            
                    
我有一个图像,悬停时,使用visibility: visible在其中显示了两个元素。我需要此图像在悬停时具有0.4的不透明度,但其中不包含任何元素。

<aside class="apartment">
  <h2>Adipiscing elit, sed diam nonummy nibh euismod</h2>
  <a href="#" class="button">Read More</a>
</aside>
<img class="essentials" src="assets/level-3-image-7.jpeg" alt="An open travelling case with clothes, a camera and other necessities in it">
</section>

.apartment {
  background: url("assets/level-3-image-6.jpeg");
  background-position: 0 90%;
  background-size: cover;
  width: 48.5%;
  height: 62.015rem;
  position: relative;
  float: left;
}

.apartment h2 {
  position: absolute;
  text-align: center;
  width: 26rem;
  top: 28%;
  left: 25%;
  visibility: hidden;
}

.apartment .button {
  position: absolute;
  top: 65%;
  left: 37%;
  visibility: hidden;
}

.apartment:hover {
  filter: opacity(0.4);
}

.apartment:hover h2{
  visibility: visible;
}

.apartment:hover .button{
  visibility: visible;
}


我知道有人问过这个问题,但我找不到适合自己答案的问题,我的.apartment类需要保持position:relative的位置来放置文本。

编辑1:
**关于MOD的编辑,当我设置以下内容时,第一个答案不起作用:

.apartment:hover {
  background-color: rgba(0,0,0,0.5);
}


第二个答案是关于定位,我明确要求不要使用它。

编辑2:
从在reddit上发布发现答案。
https://jsfiddle.net/0wdL14an/

最佳答案

您不能仅靠CSS真正做到这一点,因为更改父元素的不透明度当然会改变其子元素的不透明度。您可以使用所需的不透明度创建第二张相同的图像,然后使用jquery在悬停时将其换出,如下所示:

$(“.apartment”).hover(function(){
   $(this).css(“background”,”url(/path/to/new/image.png)”);
}, function(){
  $(this).css(“background”,”url(/path/to/old/image.png)”);
});

09-17 07:05