繁体   English   中英

如何延迟图像的加载,以便可以在加载图像之前2或3秒钟显示loading.gif? (使用jQuery / javascript)

[英]How do I delay the loading of an Image, so that i can display a loading.gif for 2 or 3 seconds before the image loads? (using jQuery/javascript)

我有两个图像:

-loading.gif(正在加载动画)

-scenery.jpeg(这是我要在加载过程之后显示的内容);

因为scenery.jpeg是一个小文件,所以使用load()函数只会跳过loading.gif

所以,当我单击按钮时,如何在它加载Scene.jpeg之前显示loading.gif 3秒钟?

提前谢谢! :d

所以我有这个HTML文件:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>

$(document).ready(function(){
    $("#loading , #picture").hide();

    $("#button1").click(function(){
        /* the loading.gif shows then after 3 seconds scenery.jpeg will use fadeIn() */
    });
});
</script>

</head>

<body>
<button id="button1">Click Me!</button>
<img id="loading" src="loading.gif"/>>
<img id="picture" src="scenery.jpeg"/>
</body>
</html>

在这种情况下,您可以使用delay()

$("#button1").click(function(){
    $("#loading").fadeIn().delay(3000).fadeOut('slow', function() {
       $(this).next().fadeIn() 
    });
});

演示

试试这个:

$('#loading, #picture').hide();
$('#button1').on('click', function() {
  $('#loading').show();
  setTimeout(function() {
    $('#loading, #picture').toggle();
  }, 3000);
});

一种方法是:

  1. 更换图像src与活动指示器src
  2. 创建新的Image对象,将其src设置为image之一。
  3. Image上添加load事件侦听器,并在setTimeout中将img src设置为所需的值。

该函数执行以下操作:

function delayLoad (img, throbber, delay) {
  var src = img.src,
      hidden = new Image();

  img.src = throbber;

  hidden.addEventListener("load", function (e) {
    setTimeout(function () {
      img.src = src;
    }, delay);
  });

  hidden.src = src;
}

像这样使用它:

delayLoad(document.querySelector("img"), "http://www.mfshop.ru/images/throbber.gif", 3000);

JSBin

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM