/** * 限制數字且最多輸入小數的位數 * @param {[type]} elem 輸入的對象 * @param {[type]} len 輸入長度 * @return {[type]} [description] */ function limitNumber(elem, len) { elem.addEventListener("input",function(e){ var result = ""; var val = e.target.value; //最後一個字符是. if (val[val.length - 1] === ".") { //若是.符號超過一個 if (val.split(".").length > 2) { val = val.slice(0, -1); } else if (val.split(".").length === 2 && val.slice(val.indexOf("."), val.length - 1).length > 2) { val = val.slice(0, val.indexOf(".") + 2) } } //存在.符號而且不止一位數 else if (val[val.length - 1] !== "." && val.indexOf(".") !== -1) { val = val.slice(0, val.indexOf(".") + (len || 2 + 1)) } e.target.value = val.replace(/[^\d\.]/g, ""); }) }
注:在調用的時候須要用原生來綁定對象函數
日期轉換函數,能夠根據需求來設置前幾天後幾天this
Date.prototype.format = function(pattern) { function zeroize(num) { return num < 10 ? "0" + num : num; }; var pattern = pattern; // YYYY-MM-DD 或 MM-DD-YYYY 或 YYYY-MM-DD , hh : mm : ss var dateObj = { "Y": this.getFullYear(), "M": zeroize(this.getMonth() + 1), "D": zeroize(this.getDate()), "h": zeroize(this.getHours()), "m": zeroize(this.getMinutes()), "s": zeroize(this.getSeconds()) }; return pattern.replace(/YYYY|MM|DD|hh|mm|ss/g, function(match) { switch (match) { case "YYYY": return dateObj.Y; case "MM": return dateObj.M; case "DD": return dateObj.D; case "hh": return dateObj.h; case "mm": return dateObj.m; case "ss": return dateObj.s; }; }); }; Date.prototype.past = function(pattern, pastDays) { function zeroize(num) { return num < 10 ? "0" + num : num; }; var pastday = new Date((this - 0) - 1000 * 60 * 60 * 24 * pastDays); var pattern = pattern; // YYYY-MM-DD 或 MM-DD-YYYY 或 YYYY-MM-DD , hh : mm : ss var dateObj = { "Y": pastday.getFullYear(), "M": zeroize(pastday.getMonth() + 1), "D": zeroize(pastday.getDate()), "h": zeroize(pastday.getHours()), "m": zeroize(pastday.getMinutes()), "s": zeroize(pastday.getSeconds()) }; return pattern.replace(/YYYY|MM|DD|hh|mm|ss/g, function(match) { switch (match) { case "YYYY": return dateObj.Y; case "MM": return dateObj.M; case "DD": return dateObj.D; case "hh": return dateObj.h; case "mm": return dateObj.m; case "ss": return dateObj.s; }; }); }; Date.prototype.yestoday = function(pattern) { return this.past(pattern, 1); }; Date.prototype.tomorrow = function(pattern) { return this.past(pattern, -1); };
單位自動轉換prototype
function getKit(array,radix,units){ var result = []; //單位轉換 function getUnit(array){ var temp = {}; var unit = ['byte','KB','MB','GB','TB']; //存儲全部配置單位的最大值 function max(){ var str=[]; for(var i=1;i<unit.length+1;i++){ var arr = Math.pow(radix,i); str.push(arr); } return str; }; //計算索引 var index = max(); for(var i=0;i<index.length;i++){ if(index[i] > array ){ temp.num=(array / Math.pow(radix,i)).toFixed(2), temp.unit = unit[i]; break; } } return temp; } for(var i=0;i<array.length;i++){ result.push(getUnit(array[i])); } return result; }