加载器图片直到背景图片完全加载完成

5

我正在尝试使用jquery实现一个加载器,直到整个背景图片完全加载。我已经尝试了各种方法来做到这一点。由于图像在CSS中指定,因此我无法指定确切的图像ID或类。最终我做到了这一点,

$(window).load(function() {
   $(".loader").fadeOut("slow");
})

但是这样做会在窗口加载时发生。我希望它在图像完全加载之前发生。 而背景图片位于以下部分。

<div class="loader"></div>
    <div class="test_banner services_banner">
</div>

如果有人能伸出援手来管理这个案例,那将是非常好的。提前感谢。


考虑使用任何“lazyload”插件。没有必要重新发明轮子。 - Aziz
请发布一个完整的示例(例如jsfiddle),包括标记和css。很难想象它的样子以及它应该是什么样子。 - Constantin Groß
1
从CSS中获取背景图像,创建一个具有相同文件名的新图像,当它加载完成后,移除加载器等。 - adeneo
2个回答

9
也许你可以使用多个背景图片。
示例:

div {
  height:90vh;
    width:90vw;
  background:url(http://lorempixel.com/1200/800/nature/) center,
    url(http://www.jqueryscript.net/demo/Simple-Customizable-jQuery-Loader-Plugin-Center-Loader/img/loader1.gif) center center no-repeat ;/* this works once/untill image has been loaded */
<div></div>

在大图片没有加载出来之前,GIF背景会一直存在,但会被绘制在大图片的后面。


谢谢你的帮助。我尝试了你的建议。但是在按照这个方法时,它会逐步显示图像加载的步骤。我想要的是在完全加载后仅显示主要图像。就像用图像替换加载器一样。 - Muneer Muhammed
@MuneerMuhammed,看起来这是一个老问题,但渐进式(交错式)JPG可以避免这种情况,它可以更快地加载图像,然后在完全加载之前逐步增加分辨率,以避免逐位显示。像Photoshop、GIMP等许多其他程序都有这个选项。甚至还有在线工具:https://coding.tools/progressive-jpeg,https://www.imgonline.com.ua/eng/make-jpeg-progressive-without-compression.php,... - G-Cyrillus

0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Create a "Please Wait, Loading..." Animation</title>
<style>
    .overlay{
        display: none;
        position: fixed;
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        z-index: 999;
        background: rgba(255,255,255,0.8) url("http://www.jqueryscript.net/demo/Simple-Customizable-jQuery-Loader-Plugin-Center-Loader/img/loader1.gif") center no-repeat;
    }
    body{
        text-align: center;
    }
    /* Turn off scrollbar when body element has the loading class */
    body.loading{
        overflow: hidden;   
    }
    /* Make spinner image visible when body element has the loading class */
    body.loading .overlay{
        display: block;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
// Initiate an Ajax request on button click
$(document).on("click", "button", function(){
    // Adding timestamp to set cache false
    $.get("/examples/php/customers.php?v="+ $.now(), function(data){
        //$("body").html(data);
    });       
});

// Add remove loading class on body element depending on Ajax request status
$(document).on({
    ajaxStart: function(){
        $("body").addClass("loading"); 
    },
    ajaxStop: function(){ 
        $("body").removeClass("loading"); 
    }    
});
</script>
</head>
<body>
    <button type="button">Get Customers Details</button>
    <div class="overlay"></div>
</body>
</html> 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接