javascript 在 div 中显示加载 gif,直到 div 从其他页面加载内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27624825/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:43:27  来源:igfitidea点击:

Display a loading gif in a div until div loads content from other page

javascriptphpjquery

提问by A.V.

I am loading a page mypage.php and in div1 I include example.php from the same server.

我正在加载一个页面 mypage.php 并在 div1 中包含来自同一服务器的 example.php。

The script is :

脚本是:

    <script>
$(document).ready(function(){

    $("#div1").load("example.php");
  });

</script>  

How can I add a loading.gif in while example.php is loading the content? I want to show the loading.gif only until the content loads.

如何在example.php加载内容时添加loading.gif?我只想在内容加载之前显示 loading.gif。

回答by miglio

you have to set a img tag display: none like:

你必须设置一个 img 标签 display: none like:

html:

html:

<div id="img-load">
<img src="loading.gif" />
</div>

script:

脚本:

loader = function(){
    $('#img-load').show();
    $( "#result" ).load( "example.php", function() {
      $('#img-load').hide();
    });
}
loader();

回答by Suchit kumar

try using like this:

尝试使用这样的:

$(document).ready(function(){
    $('#imageId').show();// imageId is id to your gif image div
    $('#div1').on('load','example.php',function(){
    $('#imageId').hide();// hide the image when example.php is loaded
  }
});

回答by Ulysnep

This method worked for me:

这种方法对我有用:

HTML

HTML

<div id="load"><img src="loading_animation.gif" /></div>
<div id="content">Display content once loaded</div>

Javascript

Javascript

<script type="text/javascript">
$(document).ready(function() {

   $('#load').show(); // Show loading animation
   $('#content').hide(); // Hide content until loaded

$(window).load(function() {

$.ajax({
  post: "GET",
  url: "your_file.php" // File that you're loading

}).done(function() {

  alert("Finished!"); // Alert message on success for debugging
  $('#load').hide(); // Hide loading animation
  $('#content').show(); // Show content

}).fail(function() {

  alert("Error!"); // Alert message if error for debugging

    });
  });
});
</script>