【问题标题】:Grayscale only button background but not text [duplicate]仅灰度按钮背景但不是文本[重复]
【发布时间】:2017-11-03 17:49:09
【问题描述】:

我有几个带有不同背景图像的按钮。 我想实现在默认情况下对它们进行灰度过滤,并在悬停时删除灰度过滤器。

我已经有了,但问题是按钮的文本也是灰色的,我想避免这种情况。 我不知道如何只在按钮背景上应用灰度滤镜,而不是在文本上。

现在我有一个用于按钮的主要 css 类

.box {
-webkit-filter: grayscale(100%);
filter: grayscale(100%);
position:relative;
color: red;
cursor:pointer;
text-align: center;
width: 160px;
height: 160px;
}
.box:hover {
-webkit-filter: grayscale(0%);
filter: grayscale(0%);
color: blue;
}

我在 html 代码中为每个按钮应用背景

<button onclick="buttonFunction()" button class="button box" style="background: url(background1.jpg); background-size: 100%;" >Gray button text:( </button>

知道如何添加灰度过滤器按钮背景并使按钮文本保持彩色吗?

谢谢

【问题讨论】:

  • 使用伪元素并仅对其应用过滤器。它不会影响文本。

标签: css button text background grayscale


【解决方案1】:

filter 属性应用于元素将影响该元素的子元素。您将无法为子级取消设置/重置过滤器属性。

如果您不想/不能在其他答案中使用pseudoelement 方法,那么您可以更改您的 HTML 以创建您想要的效果。

将图像添加为按钮中的img 元素,并将文本放置在跨度中。然后,您可以将filter 应用于img

.box {
  cursor: pointer;
  width: 160px;
  height: 160px;
  position: relative;
  padding: 0;
  display: inline-flex;
  justify-content: center;
  align-items: center;
}

.box img {
  -webkit-filter: grayscale(100%);
  filter: grayscale(100%);
  position: absolute;
  max-width: 100%;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.box:hover img {
  -webkit-filter: grayscale(0%);
  filter: grayscale(0%);
}

.text {
  color: red;
  z-index: 1;
}

.box:hover .text {
  color: blue;
}
<button onclick="buttonFunction()" button class="button box"><img src="https://unsplash.it/200x200"><span class="text">Gray button text:(</span></button>

【讨论】:

  • 谢谢,这就是我要找的:)干杯
【解决方案2】:

正如 Temani Afif 还指出的,伪元素是你的选择,尽管我想添加一些不同的定位方式,我认为这可能更精确,更容易适应响应式设计。

关键部分是使 .box 具有相同的高度和行高,这也将是我们的 :after 内容的高度。然后绝对定位(0-0-0-0)会自动居中。

.box {
  position: relative;
  color: #ff0000;
  text-align: center;
  width: 300px;
  height: 300px;
  line-height:300px;
}

.box:before {
  content: ' ';
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  filter: grayscale(100%);
  background: url(https://upload.wikimedia.org/wikipedia/commons/thumb/e/e9/16777216colors.png/220px-16777216colors.png);
  background-size: cover;
}

.box:hover:before {
  filter: grayscale(0%);
}

.box:after {
  content: 'Text Text Text';
  position: absolute;
  left:0;
  bottom:0;
  right:0;
  top:0;
  display: inline-block;
  vertical-align: middle;
}
  <button type="button" class="box">Button</button>  

【讨论】:

  • 在您的情况下,无需指定后元素的高度。使用顶部/底部就足够了。此外,您不是在按钮上应用您的样式,而是在按钮的容器上应用。这将是令人困惑的,因为我们无法再单击使其无用的按钮
  • @TemaniAfif 你是绝对正确的!我留在那里的高度,因为旧的 IE 可以使用不固定的高度伪,但是单击按钮将是一个非常糟糕的损失。很好的收获,非常感谢!
猜你喜欢
  • 2018-10-29
  • 2010-10-12
  • 2013-11-30
  • 2011-10-24
  • 1970-01-01
  • 2018-03-02
  • 2017-02-15
  • 2014-02-26
相关资源
最近更新 更多