如何在不创建图像元素的情况下在元素上叠加图像



假设我有一个HTML结构,比如

<div class="outer">
    <div class="inner">
        <h1>Here's a headline</h1>
        <p>Here's some text</p>
    </div>
    <div class="inner">
        <p>Blah blah</p>
    </div>
</div>

我希望 gif https://www.wpfaster.org/wp-content/uploads/2013/06/loading-gif.gif 在将类loading添加到outer时覆盖整个事情。有没有办法用伪元素做到这一点?添加background-image的问题在于它位于内部元素的后面。

这应该非常接近您要查找的内容。可能需要调整背景颜色。

.CSS:

.outer {
  position: relative;
}
.outer.loading:before {
  background: #fefefe url('https://www.wpfaster.org/wp-content/uploads/2013/06/loading-gif.gif') center no-repeat;
  background-size: contain;
  content: "";
  display: inline-block;
  position: absolute;
  width: 100%;
  height: 100%;
  z-index: 9999;
}

演示:https://jsfiddle.net/hopkins_matt/ac5jr5nq/

这里有一种方法可以做到这一点:

.loading .inner { visibility: hidden; }

.loading {
  background-image: url('https://www.wpfaster.org/wp-content/uploads/2013/06/loading-gif.gif');
  background-size: contain;
  background-repeat: no-repeat;  
}
.loading .inner { visibility: hidden; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="outer">
    <div class="inner">
        <h1>Here's a headline</h1>
        <p>Here's some text</p>
    </div>
    <div class="inner">
        <p>Blah blah</p>
    </div>
</div>
<button onclick="$('.outer').toggleClass('loading')">Toggle</button>

最新更新