将背景图像过渡为灰色

Transition background-image to grey

试图使背景图像平滑淡出透明,文本不透明度不变,但我只实现了 on/off 过渡。 不透明过渡在这里不起作用,因为我需要文本保持不透明。想过如何做到这一点吗?

这是我的代码:

.grid {
  margin: 0;
  padding: 0;
  width: 500px;
  height: 250px;
}

.flexbox {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  overflow: hidden;
}

#one {
  width: 250px;
  height: 250px;
  background-color: red;
  background: url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
  background-repeat: no-repeat;
  background-position: 40%;
}

#one:hover {
  background: linear-gradient(rgba(255, 255, 255, 0.5), rgba(255, 255, 255, 0.5)), url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
  background-repeat: no-repeat;
  background-position: 40%;
  height: 250px;
}
<div class="grid">
  <div class="flexbox">
    <div id="one">
      <div id="textbox">
        I need this picture to smoothly fade into transparent (grey) and this text to stay opaque.
      </div>
    </div>
  </div>
</div>

您可以尝试使用 :: after 标签,这将帮助您实现预期效果。

一定要记住content = "",没有它图片就出不来。 还要记住正确设置负责图层位置的 z-index。

下面是您的示例的解决方案:

.grid {
  margin: 0;
  padding: 0;
  width: 500px;
  height: 250px;
}

.flexbox {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  overflow: hidden;
}

#one {
  width: 250px;
  height: 250px;
  position: relative;
}

#one::after {
  position: absolute;
  z-index: 1;
  width: 100%;
  height: 100%;
  background: url('https://doorcountypulse.com/wp-content/uploads/2018/03/1-PP-3-9-18-Raccoon-at-cracked-corn-660x440.jpg');
  background-repeat: no-repeat;
  background-position: 40%;
  left: 0;
  top: 0;
  content: "";
transition: opacity 0.3s, visibility 0.3s;
}

#textbox {
  z-index: 2;
  position: relative;
}

#one:hover::after {
  opacity: 0;
  transition: opacity 0.3s, visibility 0.3s;
}
<div class="grid">
  <div class="flexbox">
    <div id="one">
      <div id="textbox">
        I need this picture to smoothly fade into transparent (grey) and this text to stay opaque.
      </div>
    </div>
  </div>
</div>