我們在加載一些比較大的網頁的時候,經常網卡的等原因,加載很慢,這個時候網站頁面是空白或者不完整的,那么我們需要一種加載動畫來改善用戶體驗。
下面我們就開始插件的開發,直接上代碼,代碼有詳細注釋。
代碼:
/*頁面加載logo動畫插件*/
;(function (w, undefined) {
/*創建樣式*/
var style = w.document.createElement('style');
style.type = 'text/css';
style.innerHTML = "@keyframes lds-ripple{0%{top:94px;left:94px;width:0;height:0;opacity:1}100%{top:17px;left:17px;width:154px;height:154px;opacity:0}}@-webkit-keyframes lds-ripple{0%{top:94px;left:94px;width:0;height:0;opacity:1}100%{top:17px;left:17px;width:154px;height:154px;opacity:0}}.lds-ripple div{box-sizing:content-box;position:absolute;border-width:6px;border-style:solid;opacity:1;border-radius:50%;-webkit-animation:lds-ripple 1s cubic-bezier(0,0.2,0.8,1) infinite;animation:lds-ripple 1s cubic-bezier(0,0.2,0.8,1) infinite}.lds-ripple div:nth-child(1){border-color:#36f}.lds-ripple div:nth-child(2){border-color:#c90;-webkit-animation-delay:-0.5s;animation-delay:-0.5s}.lds-ripple{width:200px!important;height:200px!important;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%)}#vj-loading{width:100%;height:100%;position:absolute;left:0;top:0;background-color:rgba(0,0,0,.4)}";
/*創建根div節點*/
var root = w.document.createElement('div');
root.setAttribute('id', 'vj-loading');
/*將樣式節點加入根節點*/
root.appendChild(style);
/*創建加載動畫div*/
var ripple = w.document.createElement('div');
/*添加class樣式*/
ripple.classList.add('lds-ripple');
/*添加兩個div節點*/
ripple.appendChild(w.document.createElement('div'));
ripple.appendChild(w.document.createElement('div'));
/*將ripple節點添加到根節點*/
root.appendChild(ripple);
/*將根節點添加到body中*/
w.document.body.appendChild(root);
/*監聽頁面加載事件*/
w.document.onreadystatechange = function () {
if (w.document.readyState === 'complete') {
w.document.body.removeChild(root);
}
}
})(window);
注意:該文件最好引入在body標簽開頭效果最佳,切記不要在head中引入,因為那個時候還檢測不到body節點。
到此,插件開發完畢,想要在那個頁面使用就引入該js文件吧。