显示和隐藏加载GIF的最佳做法

时间:2016-09-17 14:13:11

标签: javascript jquery css loading

我有一个页面,我在其中单击一个按钮将另一个页面的内容加载到div中。 当我点击按钮时,我想要显示一个加载的gif,当然,当另一页的内容已完全加载到div“maincontent”时,我想要消失。下面是我目前的代码 - 这是实现这种效果的最佳实践 - 不知何故,我认为必须有更好的方法来实现它吗?

的index.php:

<html>
  <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

    <script type="text/javascript">

      $(document).ready(function() { 
        $('#loading').hide();

        $(document).on('click', '.menu1', function(){
          $('#loading').show();
          $('.maincontent').load("1.php");
        });

      });
    </script>

    <style>
      #loading {
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        position: fixed;
        display: block;
        opacity: 0.7;
        background-color: #fff;
        z-index: 99;
        text-align: center;
      }

      #loading-image {
        position: absolute;
        top: 25%;
        left: 50%;
        z-index: 100;
      }
    </style>

  </head>
  <body>
    <button class="menu1">Click</button>
    <div class="maincontent">
      <div id="loading">
        <img id="loading-image" src="images/ajax-loader.gif" alt="Loading..." />
      </div>
    </div>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以使用.ajaxStart.ajaxStop事件分别显示和隐藏加载程序。请查看下面的代码段。

$(document).ready(function() { 
    $('#loading').hide().ajaxStart( function() {
        $(this).show();  // show Loading Div
    } ).ajaxStop ( function(){
        $(this).hide(); // hide loading div
    });

    $(document).on('click', '.menu1', function(){
      $('.maincontent').load("1.php");
    });
});