浅谈网站头部加载进度条的实现---NProgress

我们在移动端的浏览器上经常能看到页面上方有一个进度条加载,pc端网页也有,例如打开我的github主页:https://github.com/fzg2lj 点击导航栏上的stars,就会出现一个加载进度条。实现这种效果有两种方式。

第一种:利用ajax全局请求方式

代码如下

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>主页面</title>
  <link rel="stylesheet" href="bootstrap.css">
  <link rel="stylesheet" href="../nprogress.css">
  <style>
    .loading {
      display: none;
      position: fixed;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
      background-color: rgba(0, 0, 0, .6);
      font-size: 30px;
    }
  </style>
  <script src="../nprogress.js"></script>
</head>
<body>
  <div class="container pt-4">
    <h1>会员中心</h1>
    <hr>
    <div class="row">
      <aside class="col-md-3">
        <div class="list-group">
          <a class="list-group-item list-group-item-action" href="index.html">我的资料</a>
          <a class="list-group-item list-group-item-action" href="cart.html">我的购物车</a>
          <a class="list-group-item list-group-item-action" href="orders.html">我的订单</a>
        </div>
      </aside>
      <main id="main" class="col-md-9">
        <h2>我的个人资料</h2>
        <hr>
      </main>
    </div>
  </div>
  <div class="loading">正在玩命加载中...</div>
  <script src="../jquery.js"></script>
<script>
$(function($){
$(document)
        .ajaxStart(function () {
       //只要有 ajax 请求发生 就会执行
         $('.loading').fadeIn()
        // 显示加载提示
     console.log('注意即将要开始请求了')
       })
     .ajaxStop(function () {
       // 只要有 ajax 请求结束 就会执行
        $('.loading').fadeOut()
       // 结束提示
       console.log('请求结束了')
       })
       });
       </script>

不过推荐第二种方式,有一个现成的轻量级进度加载库 http://ricostacruz.com/nprogress/

第二种:NProgress

$(document)
        .ajaxStart(function () {
          NProgress.start()
        })
        .ajaxStop(function () {
          NProgress.done()
        })

只要将第二种的代码替换掉上面第一种的代码,在点击跳转其他页面的时候,就会显示加载进度条

猜你喜欢

转载自blog.csdn.net/weixin_44442095/article/details/86354428