改变div背景图片的不透明度

时间:2016-09-20 20:18:49

标签: javascript jquery html css3

我有一个带有一些

文本和背景图像的DIV。我想减少背景图像的不透明度。但是当我对DIV应用不透明度时,它会影响DIV中的文本。如何在不更改DIV中文本的不透明度的情况下更改背景图像的不透明度?

我有这个代码我从stackoverflow上的另一个问题得到,我用它来减少另一个div的不透明度,但我不知道如何修改它来实现上述问题。

function convertHex(hex,opacity){
hex = hex.replace('#','');
r = parseInt(hex.substring(0,2), 16);
g = parseInt(hex.substring(2,4), 16);
b = parseInt(hex.substring(4,6), 16);

result = 'rgba('+r+','+g+','+b+','+opacity/100+')';
return result;
}


$(".add_to_cart_button").click(function() {

$(".cart-contents").css("background-color",convertHex('#f47d32',40));
});

2 个答案:

答案 0 :(得分:1)

第一步是将z-index: -1;position: relative;添加到您的后方div css:

改变不透明背景的方法:

$("#backDiv").css("opacity", "0.4");
$("#backDiv").css({ opacity: 0.4 });
$("#backDiv").fadeTo("slow", 0.4);
$("#backDiv").fadeTo(1000, 0.4); // fist parameter is animate time in ms

测试按钮可能会在动画后执行一些操作:

$("#buttonTest").click(function() {
  $("#backDiv").fadeTo("slow" , 0.4, function() {
    // Animation complete. You can add some action.
  });
});

我希望它有所帮助...

祝你好运!

答案 1 :(得分:0)

我认为以下是你正在寻找的东西:



#d1 {
  background: url("http://666a658c624a3c03a6b2-25cda059d975d2f318c03e90bcf17c40.r92.cf1.rackcdn.com/unsplash_527bf56961712_1.JPG");
  height: 200px;
  width: 500px;
  position: relative;
}

.overlay {
  position: absolute;
  top: 0;
  left: 0;
  background-color: rgba(255, 255, 255, 0.7);
  height: 100%;
  width: 100%;
  display: block;
}

#d2 {
  color: red;
  position: relative;
}

<div id="d1">
  <div class="overlay"> </div>
  <div id="d2">
    Test content
  </div>
</div>
&#13;
&#13;
&#13;

相关问题