先展現一下已經實現的效果:javascript
預覽地址:http://dtdxrk.github.io/js-plug/LoadingBar/index.htmlcss
看到手機上的瀏覽器內置了頁面的加載進度條,想用在pc上。html
網上搜了一下,看到幾種頁面loading的方法:java
1.在body頭部加入loading元素,在body頁腳寫入腳本讓loading元素消失。jquery
2.基於jquery,在頁面的不一樣位置插入腳本,設置滾動條的寬度。css3
簡單分析一下:git
第一個明顯不是我想要的。github
第二個要在body前加載jquery,而後還要使用到jquery的動畫方法,性能確定達不到最優的狀態。web
上面的方法2實際上是能夠使用的方法,可是我不想在頁面前加載jquery,怎麼辦?express
很簡單,本身用原生的方法寫一個。
給元素添加css3的動畫屬性,讓他能在改變寬度的時候有動畫效果。
transition:all 1s;-moz-transition:all 1s;-webkit-transition:all 1s;-o-transition:all 1s;
在頁面插入一段style,裏面有元素的css和一個css3動畫暫停的類
.animation_paused{ -webkit-animation-play-state:paused; -moz-animation-play-state:paused; -ms-animation-play-state:paused; animation-play-state:paused; }
而後在頁面裏不一樣的位置調用方法,設置滾動條的寬度便可,須要注意的是方法的引用要在<head></head>裏
<div id="top"></div> <script>LoadingBar.setWidth(1)</script> <div id="nav"></div> <script>LoadingBar.setWidth(20)</script> <div id="banner"></div> <script>LoadingBar.setWidth(40)</script> <div id="main"></div> <script>LoadingBar.setWidth(60)</script> <div id="right"></div> <script>LoadingBar.setWidth(90)</script> <div id="foot"></div> <script>LoadingBar.setWidth(100)</script>
插件源碼:
/* ======================================================================== LoadingBar 頁面加載進度條 @auther LiuMing @blog http://www.cnblogs.com/dtdxrk demo 在body裏填寫須要加載的進度 LoadingBar.setWidth(number) ======================================================================== */ var LoadingBar = { /*初始化*/ init:function(){ this.creatStyle(); this.creatLoadDiv(); }, /*記錄當前寬度*/ width:0, /*頁面裏LoadingBar div*/ oLoadDiv : false, /*開始*/ setWidth : function(w){ if(!this.oLoadDiv){this.init();} var oLoadDiv = this.oLoadDiv, width = Number(w) || 100; /*防止後面寫入的width小於前面寫入的width*/ (width<this.width) ? width=this.width : this.width = width; oLoadDiv.className = 'animation_paused'; oLoadDiv.style.width = width + '%'; oLoadDiv.className = ''; if(width === 100){this.over(oLoadDiv);} }, /*頁面加載完畢*/ over : function(obj){ setTimeout(function(){ obj.style.display = 'none'; },1000); }, /*建立load條*/ creatLoadDiv : function(){ var div = document.createElement('div'); div.id = 'LoadingBar'; document.body.appendChild(div); this.oLoadDiv = document.getElementById('LoadingBar'); }, /*建立style*/ creatStyle : function(){ var nod = document.createElement('style'), str = '#LoadingBar{transition:all 1s;-moz-transition:all 1s;-webkit-transition:all 1s;-o-transition:all 1s;background-color:#f90;height: 3px;width:0; position: fixed;top: 0;z-index: 99999;left: 0;font-size: 0;z-index:9999999;_position:absolute;_top:expression(eval(document.documentElement.scrollTop));}.animation_paused{-webkit-animation-play-state:paused;-moz-animation-play-state:paused;-ms-animation-play-state:paused;animation-play-state:paused;};' nod.type = 'text/css'; //ie下 nod.styleSheet ? nod.styleSheet.cssText = str : nod.innerHTML = str; document.getElementsByTagName('head')[0].appendChild(nod); } }