(function(){
var gcld_but = document.getElementById("gcld_but"),
gcld_but_li = gcld_but.getElementsByTagName("li"),
gcld_box = document.getElementById("gcld_box"),
close_btn = document.getElementById("close_btn"),
gcld_btn = document.getElementById("gcld_btn"),
box = document.getElementById("box"),
mask = document.getElementById("mask"),
len = gcld_but_li.length,
gcld_but_a,
i,
s_height = document.documentElement.scrollHeight||document.body.scrollHeight;
o_height = null,
o_width = null,
on = 0; ------------------------>>>>>>>>>>>>>>>>>>>>>變量盡量寫在開頭,防止滾動時候每次執行函數就取DOM元素,浪費性能。
mask.style.height = s_height+"px";
/*水平垂直居中函數*/
function centered_box(){
var s_top = document.body.scrollTop||document.documentElement.scrollTop,
c_height = document.documentElement.clientHeight||document.body.clientHeight,
c_width = document.documentElement.clientWidth||document.body.clientWidth,
left,
top;
if( !o_height ){------------------------------>>>>>>>>>>>>>>>>>>>取一次DOM元素后放在變量里(頁面不關閉就一直存在),下次執行函數就不用取了。
o_height = box.offsetHeight;
o_width = box.offsetWidth;------------------->>>>>>>>>>>>>>>>有些瀏覽器在元素display:none時取不到寬高,點擊按鈕顯示該元素后再執行函數,所以寫在函數里面一定能取到。
}
left = (c_width - o_width)/2 + "px";
top = (c_height/2 - o_height/2 +s_top) + "px";
box.style.left = left;
box.style.top = top;
}
/*點擊打開彈窗*/
for(i=0; i<len; i++){
gcld_but_a = gcld_but_li[i].getElementsByTagName("a")[0];
gcld_but_a.onclick = function(){
gcld_box.style.display = "block";
on = 1;-------------------->>>>>>>>>>>>>>>>>>>>>>>加個開關,確保只讓點擊的時候執行彈窗函數。
centered_box();
}
}
/*關閉彈窗*/
close_btn.onclick = gcld_btn.onclick = function(){
gcld_box.style.display = "none";
on = 0;
};
window.onscroll = window.onresize = function(){
if(on){
centered_box();
}
};
})();
總結:1:定義的變量盡量寫在程序的上方----規范
2:(從執行流的角度)功能實現后----(從性能的角度)對程序進行優化。
3:性能優化
1、防止重復獲取DOM元素
2、防止重復執行代碼函數
3、寫法考慮兼容性