针对background-image div的Lazyload插件导致div中包含的内容在加载图像时闪烁

时间:2016-08-25 13:23:06

标签: javascript jquery html jquery-lazyload

我有一个小但烦人的问题。我正在使用JQuery的Lazyload插件(Mika Tuupola - here),我遇到了一个问题,即在div background-image属性上使用fadeIn效果会导致内部内容在图像最终加载时闪烁。它基本上在图像加载时重新加载内容。我该如何避免这种情况?

我的html摘录:

<div class="wrap" id="wrap">    
    <div class="bg-image" data-original="images/image_1.jpg">
         <h1>Some title here</h1>
    </div>
    <div class="bg-image" data-original="images/image_1.jpg">
         <h1>Some other title here</h1>
    </div>
    <div class="bg-image" data-original="images/image_1.jpg">
         <h1>another title here</h1>
    </div>
</div>

我对Lazyload的JS使用是针对容器元素的,因为我上面重复了几次结构(加载相同的图像):

$("div.bg-image").lazyload({
    container: $("#wrap"),
     threshold: 200,
    effect: "fadeIn"
});

在大多数情况下,它运作良好,但闪烁有点偏。希望这是足够的细节,我会看看我是否可以得到一个样本小提琴(你可能不得不忍受我...)

1 个答案:

答案 0 :(得分:1)

我是jQuery的另一个lazy load plugin的创建者。你无法用这种方式解决问题。问题是,当外部div消失时,内容总是会褪色。你无能为力阻止这一点。

一种可能的解决方案是将背景放在内容框背面的另一个div中。所以它将作为背景可见,但事实并非如此。所以背景有一个额外的元素,可以单独褪色。然后内容也不会褪色。

以下是我的意思的快速示例:

$(".bg").lazy({
  threshold  : 0,
  effect     : "fadeIn",
  effectTime : 500
});
.wrap > div {
  width: 500px;
  height: 250px;
  position: relative;
}
.bg {
  width: 500px;
  height: 250px;
  position: absolute;
  z-index: -1;
}
h1 {
  text-align: center;
  line-height: 250px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.lazy/1.7.3/jquery.lazy.min.js"></script>

<div class="wrap" id="wrap">
  <div>
    <div class="bg" data-src="http://dummyimage.com/500x250/ff00a2/ff00a2&text=1"></div>
    <h1>Some title here</h1>
  </div>
  <div>
    <div class="bg" data-src="http://dummyimage.com/500x250/0099ff/0099ff&text=2"></div>
    <h1>Some other title here</h1>
  </div>
  <div>
    <div class="bg" data-src="http://dummyimage.com/500x250/45d104/45d104&text=3"></div>
    <h1>another title here</h1>
  </div>
</div>