提问者:小点点

CSS过渡仅在背景中淡出,而不是子div


我有这样的情况:

null

setTimeout(function() {


  // Set BG image
  var bg_content = document.querySelector('.content_top');
  bg_content.style.background = "linear-gradient(0deg,#000 0,rgba(0,0,0,.7) 35%,rgba(0,0,0,.4) 50%,rgba(0,0,0,0) 100%),url(https://upload.wikimedia.org/wikipedia/commons/8/8f/Example_image.svg) no-repeat";
  bg_content.style.backgroundSize = "cover";
  bg_content.style.backgroundPosition = "center";
  bg_content.classList.add("fade-in");

}, 1500);
.fade-in {
  opacity: 1;
  animation-name: fadeInOpacity;
  animation-iteration-count: 1;
  animation-timing-function: ease-in;
  animation-duration: 0.5s;
}

@keyframes fadeInOpacity {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.main_header {
  color: blue;
  text-align: center;
  font-size: 30px;
}

.content_top {
  height: 300px;
}
<div class="content_top">
  <div class="main_header"><span class="vertical_line"></span>
    <p data-transkey="main_header_notrans"><span class="tino">Some header</span> <br> some text</p>
  </div>
</div>

null

.content_top有一个背景图像,我希望在加载页面时将其淡出,但我不希望.main_header也受到影响。当前,这会导致.main_header中的文本出现闪烁效果,看起来很糟糕。

下面是一个工作示例:JsFiddle


共1个答案

匿名用户

将背景移动到.content_top元素内部的新div。这将创建一个新的层,我们可以在不影响内容的情况下动画。

.content_top.main_header指定一个position:relative值。这将使.content_top成为一个相对容器,并使.main_header有可能使用z-index

在下面的片段中,我添加了一个新元素:.main_bg。这个元素将获得背景图像和动画。

.main_bg元素指定一个位置:absolute;。这将允许您将元素相互叠加,在本例中为.main_bg.main_header

null

setTimeout(function() {
  // Set BG image
  var bg_content = document.querySelector('.main_bg');
  bg_content.style.background = "linear-gradient(0deg,#000 0,rgba(0,0,0,.7) 35%,rgba(0,0,0,.4) 50%,rgba(0,0,0,0) 100%),url(https://upload.wikimedia.org/wikipedia/commons/8/8f/Example_image.svg) no-repeat";
  bg_content.style.backgroundSize = "cover";
  bg_content.style.backgroundPosition = "center";
  bg_content.classList.add("fade-in");

}, 1500);
.fade-in {
  opacity: 1;
  animation-name: fadeInOpacity;
  animation-iteration-count: 1;
  animation-timing-function: ease-in;
  animation-duration: 0.5s;
}

@keyframes fadeInOpacity {
  0% {
    opacity: 0;
  }
  100% {
    opacity: 1;
  }
}

.main_bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.main_header {
  position: relative;
  color: blue;
  text-align: center;
  font-size: 30px;
  z-index: 1;
}

.content_top {
  height: 300px;
  position: relative;
}
<div class="content_top">
  <div class="main_bg"></div>
  <div class="main_header"><span class="vertical_line"></span>
    <p data-transkey="main_header_notrans"><span class="tino">Some header</span> <br> some text</p>
  </div>
</div>