標籤:style blog http io ar color os sp for
前言
看了網上一些關於網頁進度條樣式的資料,有很多方式實現,針對其展現形式,有用圖片的,有用css2屬性clip,有用flash的,本人就學會了一種,下面就簡單來介紹一下。
css2的屬性clip
如果你不是很明白clip屬性,那麼我就用大白話來解釋一下,clip:rect(0px,0px,0px,0px)有四個值,同理是順時針方向賦值,上右下左,記錄改元素裁切方式,
例如:一個元素div,其width:300px;height:300px; clip:rect(0px,100px,60px,0px)
表示裁切的左邊距離原元素上邊緣0px;
裁切的右邊距離原始左邊緣100px;
裁切的下邊距離原始元素上邊緣是60px;
裁切的左邊距離原始元素元素左邊距離是0px;
如果明白了,那麼再來一張圖測試一下,如果設定是clip:rect(10px,100px,40px,5px)圖片應該啥樣子呢?如下
說到這裡,我就當你明白了,繼續往下說,
所以現在我們要改變的就是裁切元素的右值,讓其等於制定的寬度,那麼元素就全部呈現出來了。
設定進度條樣式
對於css我做的還是比較low的,那麼還是要貼出我很low的css代碼,
<style type="text/css"> #progressBox{width:300px;height:60px;position:absolute;left:0;border:1px solid #000;} #progressBar{background:blue;opacity:0.3;filter:alpha(opacity=30); width:300px;height:60px;position:absolute;clip:rect(0px,0px,60px,0px);left:0;top:0;} #progressText{color:Black;width:300px;height:60px;position:absolute;left:0;top:0;text-align:center; line-height:60px; font-family:Georgia;font-size:2em;font-weight:bold;}</style>
頁面元素
<body><div id="progressBox"> <div id="progressBar"></div> <div id="progressText">0%</div></div><input type="button" value="開 始" id="btn" style="position:absolute;left:50%;top:20%;"/></body>
這裡需要解釋一下為啥會有3個元素,一個是元素容器(progressBox)基本就是想突出邊框,讓使用者知道100%應該是有多長的容量,
第二個progressBar是表示不斷變化的元素背景色設定為淡藍色,
第三個是表示進度顯示的數值文本
然後現在要做的就是js指令碼
因為現在沒有與伺服器互動所以我就用setInterval來類比增長因子
timer = setInterval(progressFn, 10); function progressFn() { if (cent == max) { clearInterval(timer); } else { divbar.style.clip = "rect(0px," + cent + "px,60px,0px)"; divText.innerHTML = Math.ceil((cent / max) * 100) + "%"; cent++; } };
上邊這段js是通過改變裁切的右邊距實現展示進度條背景色,同時改變進度文本值。
XMLHttpRequest的progress事件實現前後互動的進度條顯示
利用XMLHttpRequest第二版還定義的progress事件可以知道上傳進度,來配合我們頁面前端的展示進度來真正實現有後端互動的進度條
先上代碼
var xhr = new XMLHttpRequest(); xhr.timeout = 8000; xhr.open(‘POST‘, form.action); xhr.send(formData); xhr.onreadystatechange = function () { if (xhr.readyState == 4 && xhr.status == 200) { console.log("xhr.responseText", xhr.responseText); } else { console.log("xhr.statusText", xhr.statusText); } }; xhr.onprogress = updateProgress; //xhr.upload.onprogress = updateProgress; function updateProgress(event) { if (event.lengthComputable) { var percentComplete = event.loaded / event.total; console.log(event.loaded, event.total, 300 * percentComplete); progressFn(300 * percentComplete, max); } } xhr.ontimeout = function (event) { alert(‘請求逾時!‘); }
其中的event.loaded表示當前載入了多少位元組流,而event.total表示總共有多少位元組流 得到這樣一個百分比,
然後調用我們事先定義好的progressFn()函數就ok了,感覺還是挺方便的。
當然除了這種方式還有我前面提到過的配合flash來調用我們實現定義好的函數等。
以上就是我今天想要分享的小知識點,本人水平有限,如果有錯誤和建議
還懇請指出,如果覺得對你有用,請支援一下。
用css2屬性clip實現網頁進度條