CSS與JS實現網頁載入中的動畫效果的執行個體

來源:互聯網
上載者:User
本文執行個體為大家分享了JS實現網頁載入中效果的具體代碼,供大家參考,具體內容如下

需要材料:

一張loading動畫的gif圖片

基本邏輯:

模態框遮罩 + loading.gif動圖,
預設隱藏模態框
頁面開始發送Ajax請求資料時,顯示模態框
請求完成,隱藏模態框

下面我們通過Django建立一個web應用,來簡單實踐下

實踐

1.建立一個Django項目,建立應用app01, 配置好路由和static,略。將gif動圖放到靜態檔案夾下,結構如下:

2.視圖中定義一個函數,它返回頁面test.html:

def test(request): return render(request, 'test.html')

3.test.html頁面如下:

<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <!-- 匯入css樣式 --> <link rel="stylesheet" href="/static/css/loading.css" rel="external nofollow" > <!-- 匯入jquery 和 js檔案 --> <script src="/static/plugins/jquery-3.2.1.js"></script> <script src="/static/js/loading.js"></script></head><body><h1>你好啊,朋友!</h1><hr><p id="content"> <p>正在請求伺服器資料....</p></p><!-- 模態框部分 --><p class="loading hide"> <p class="gif"></p></p></body></html>

4.CSS樣式如下:

/* 模態框樣式 */.loading { position: fixed; top: 0; bottom: 0; right: 0; left: 0; background-color: black; opacity: 0.4; z-index: 1000;}/* 動圖樣式 */.loading .gif { height: 32px; width: 32px; background: url('/static/img/loading.gif'); position: fixed; left: 50%; top: 50%; margin-left: -16px; margin-top: -16px; z-index: 1001;}

說明:

  • 通過設定position: fixed,並令上下左右為0,實現模態框覆蓋整個頁面;

  • 設定gif動態圖為背景,置中,來顯示載入效果;

  • 通過設定z-index值,令gif圖懸浮在模態框上面;

  • background-color: black;是為了看著明顯,具體使用時可以設為white;

5.JS檔案如下:

$(function () { //準備請求資料,顯示模態框 $('p.loading').show(); $.ajax({  url: "/ajax_handler.html/",  type: 'GET',  data: {},  success: function (response) {   var content = response.content;   $('#content').html(content);   //請求完成,隱藏模態框   $('p.loading').hide();  },  error: function () {   $('#content').html('server error...');   //請求完成,隱藏模態框   $('p.loading').hide();  } })});

說明:

頁面載入後,開始發送Ajax請求,從服務端ajax_handler視圖請求資料,這時顯示模態框
請求完成後,不論成功與否,隱藏模態框

6.ajax_handler視圖如下,它類比網路延遲,並返回一些字串:

from django.http import JsonResponsefrom django.utils.safestring import mark_safe # 取消字串轉義def ajax_handler(request): # 類比網路延遲 import time time.sleep(3) msg = ''' XXX ''' # 這裡你可以隨便放入一些字串 return JsonResponse({"content": mark_safe(msg)})

效果如下:

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.