【问题标题】:Applying gray scale only to one background image using Multiple Backgrounds in CSS?使用CSS中的多个背景仅将灰度应用于一个背景图像?
【发布时间】:2020-08-20 05:33:07
【问题描述】:

是否有可能让两张背景图片在悬停时只让其中一张变成黑白?

这是一个例子:

<!DOCTYPE html>
<html>
<head>
<style> 
#example1 {
  background-image: url(img1.gif), url(img2.gif);
  background-position: right bottom, left top;
  background-repeat: no-repeat, no-repeat;
  height: 100px;
}
</style>
</head>
<body>
<div id="example1"></div>

</body>
</html>

我尝试使用filter: grayscale(100%);,但不知道如何仅将其应用于 img1.gif 而不是 img1.gif & img2.gif

【问题讨论】:

  • 抱歉,恐怕不行。
  • 你到底想做什么?它们是两张完全不同的图像,还是一张只是另一张的灰度?如果它们是不同的图像,要在哪里应用灰度?
  • @FluffyKitten 都是彩色的,其中一个必须在悬停后变成灰度
  • 你也许可以用 jQuery 来做,或者我可以给你一个非常 hack-y 的方法来用 CSS 做?
  • @FluffyKitten 也许下一个解决方案是去#example1:hover{background-image: url(img1-bw.gif), url(img2.gif); } 的方法。我认为使用 javascript 不是一个好主意,因为它会占用一些处理器时间。

标签: html css filter grayscale


【解决方案1】:

这有点骇人听闻,但您可以添加一个包含“悬停”照片的叠加层,并为其添加灰度滤镜。看看这个例子 - 它只使用了 2 张图片,而且都是彩色的。

(仅供参考,我已经为这个例子指定了 div 的高度和宽度,但这不是必需的)

#example1 {
background-image: url(https://lorempixel.com/output/nature-q-c-200-200-2.jpg), url(https://lorempixel.com/output/nature-q-c-200-200-5.jpg);
  background-position: right bottom, left top;
  background-repeat: no-repeat, no-repeat;
  height: 200px;
  width:400px;
  position:relative;
  border:1px solid #ccc;
}

#example1:hover:before {
  background-image: url(https://lorempixel.com/output/nature-q-c-200-200-5.jpg);
  background-position: left top;
  background-repeat: no-repeat;
  filter: grayscale(100%);
  content:"";
  position:absolute;
  top:0;
  bottom:0;
  left:0;
  right:0;  
  z-index:10;
}
&lt;div id="example1"&gt;&lt;/div&gt;

基本上,我们使用before 创建一个绝对定位的覆盖,覆盖整个 div 大小(无论它是什么大小)。这仅包含要在与主 div 相同的位置“变灰”的图像。它仅在悬停时使用#example1:hover:before 激活。

【讨论】:

    【解决方案2】:

    我不确定这是否是你想要的,但这是我做的:

    <!DOCTYPE html>
    <html>
    <head>
    <style> 
    #example1  {
      background-image: url("img1.jpg"), url("img2.jpg");
      background-position: right bottom, left top;
      background-repeat: no-repeat, no-repeat;
      height: 100px;
      filter: grayscale(0%);
    
    }
    #img1:hover{
        filter: grayscale(100%);
    }
    
    
    </style>
    </head>
    <body>
    <div id="example1">
      <div><img src="img1.jpg" alt="" id="img1"></div>
      <div><img src="img2.jpg" alt=""></div>
    </div>
    
    </body>
    </html>
    

    【讨论】:

    • 不幸的是图像被放入背景图像中。我知道这个选项,但这不是我想要的。不过还是谢谢
    • 我没听懂你的意思,你想在 example1 元素悬停时将 img1 变为灰度,对吗?
    • 是但不使用 img 标签。只有background-image: url("img1.jpg"), url("img2.jpg");
    猜你喜欢
    • 2013-04-26
    • 2019-08-18
    • 1970-01-01
    • 2011-12-24
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多