如何悬停div并使其背景图像慢慢消失而不影响其内部的内容?

时间:2017-06-08 19:52:30

标签: javascript jquery html css

我有一个背景色,背景图像和一些文字的div。我想,当我悬停div时,背景图像会慢慢消失,就像过渡效果一样,但文本和颜色仍然在div中可见。我对任何类型的方法都是开放的。

This is how the div should look before hover

This is how it's supposed to be while hovering

1 个答案:

答案 0 :(得分:0)

只需使用CSS添加一些DOM元素即可轻松完成此操作。

.fadebg {
  position: relative;
  height: 100px;
  width: 100px;
  background-color: red;
}
.fadebg:hover .img, .fadebg:hover img {
    opacity: 0;
}

.text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  color: white;
  z-index: 1;
}

.img {
    background-repeat: no-repeat;
  background-image: url(https://upload.wikimedia.org/wikipedia/en/b/bc/Screenshot_Snarf.jpg);
  background-size: 100px 100px;
}

.img, img {
  opacity: 1;
  height: 100px;
  width: 100px;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  overflow: hidden;
  -webkit-transition: 1s all;
  -moz-transition: 1s all;
  -ms-transition: 1s all;
  -o-transition: 1s all;
  transition: 1s all;
}
<div class="fadebg">
    <div class="text">Hi</div>
    <div class="img"></div>
</div>
<br>
<div class="fadebg">
    <div class="text">Hi</div>
    <img src="https://upload.wikimedia.org/wikipedia/en/b/bc/Screenshot_Snarf.jpg">
</div>