带有“背景图像”的div的不透明度会影响孩子,我只想影响父亲

时间:2019-03-14 19:31:33

标签: css

我有一个 window.onload = function() { document.getElementById('name1').style.display = 'none'; document.getElementById('name2').style.display = 'none'; }; function button1function(id) { document.getElementById('name2').style.display = 'none'; if (document.getElementById(id).style.display == 'none') { document.getElementById(id).style.display = 'initial'; } else { document.getElementById(id).style.display = 'none'; } } function button2function(id) { document.getElementById('name1').style.display = 'none'; if (document.getElementById(id).style.display == 'none') { document.getElementById(id).style.display = 'initial'; } else { document.getElementById(id).style.display = 'none'; } } 和一个div,我希望它的悬停效果可以更改其不透明度而不影响子元素,在这种情况下为background-image。我已经看到了类似的问题答案,但是具有背景无法解决这些问题。具有背景的元素的不透明度会影响孩子,我只想影响父亲

我该如何解决?

<p>

这是我的代码:

https://jsfiddle.net/t98mbxca/

2 个答案:

答案 0 :(得分:0)

在这种情况下,opacity可以正常工作,因为它更改了元素及其所有内容的Alpha通道。您可能需要另一种方法。看起来您只想要一个绿色渐变按钮?

我将div更改为button,并删除了HTML中的p标签。

对于背景,您可以使用纯CSS使用linear-gradient来创建background-image作为rgba的{​​{1}}颜色,以便您可以在悬停时更改Alpha(不透明度)。

.container_img {
   height: 50px;
   line-height: 50px;
   padding: 0 60px;
   border-radius: 10px;
   font-size: 20px;
   cursor: pointer;
   background-image: linear-gradient(rgba(130, 167, 99, 1), rgba(102, 146, 63, 1));
}

.container_img:hover {
   background-image: linear-gradient(rgba(130, 167, 99, 0.5), rgba(102, 146, 63, 0.5));
}
<button class="container_img">
  this is a text 
</button>

答案 1 :(得分:0)

如果要使用实际图像,最简单的方法是将背景图像移动到伪元素。

.container_img {
  position: relative;
  border: 1px solid red;
  margin-top: -14px;
  display: table;
  margin-top: 2px;
  width: 709px;
  height: 141px;
}

p {
  position: absolute;
  left: 50%;
  font-size: 50px;
}

.container_img::before {
  content: '';
  background-image: url("https://i.imgur.com/VBOZfaY.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.container_img:hover::before {
  opacity: .5;
}
<div class="container_img">
  <p>
    this is a text
  </p>
</div>