CSS:如何在悬停时从背景图像中删除带有过渡的色调?

问题描述 投票:0回答:2

我有以下HTML和CSS示例,其中的图像带有红色。当我将鼠标悬停在其上时,色度将被删除-这是通过再次插入没有色度的图像来实现的。

问题是它非常瞬时-没有过渡。我试图插入一个过渡,但似乎不起作用。

div {
  background-image: linear-gradient(to bottom,
      rgba(250, 0, 0, 0.5),
      rgba(250, 0, 0, 0.5)), url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
  height: 300px;
  width: 300px;
  background-size: 300px;
  transition: all 2s ease-out;
}

div:hover {
  background-image: url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
  transition: all 2s ease-out;
}
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>

  <body>
    <div>
    
    </div>
  </body>

</html>
html css animation css-transitions
2个回答
0
投票

您正在尝试制作background-image的动画,但无法完成,

为什么不使用after伪元素

div {
  background-image: url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
  height: 300px;
  width: 300px;
  background-size: 300px;
  position: relative;
}


div:after {
content: '';
position: absolute;
width: 100%;
height: 100%;
background-color: red;
opacity: 0.5;
transition: .5s;
}

div:hover:after {
opacity: 0;
}
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <title>Document</title>
  </head>

  <body>
    <div>
    
    </div>
  </body>

</html>

0
投票

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <style>
      .elem1 {
        background-image: linear-gradient(
            to bottom,
            rgba(250, 0, 0, 0.5),
            rgba(250, 0, 0, 0.5)
          ),
          url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
        height: 300px;
        width: 300px;
        background-size: 300px;
        transition: all 2s;
        position: relative;
      }

      .elem2 {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-image: url("https://homepages.cae.wisc.edu/~ece533/images/cat.png");
        opacity: 0;
        background-size: cover;
      }

      .elem2:hover {
        transition: all 2s;
        opacity: 1;
      }
    </style>
  </head>

  <body>
    <div class="elem1">
      <div class="elem2"></div>
    </div>
  </body>
</html>
© www.soinside.com 2019 - 2024. All rights reserved.