js小功能记录
个人日常中遇到的js小功能记录,方便查看。
/**
* 判断是否包含字符串某字符串
* @param {[type]} str [被检测的字符串]
* @param {[type]} substr [检测是否含有的字符串]
* @return {Boolean} [ture,false]
*/
function isContains(str,substr) {
return new RegExp(substr).test(str);
}
/**
* 判断文件是否是图片
* @param {[type]} fileType 文件类型,如"image/png"
* @return {Boolean}
*/
function isImageByType(fileType) {
return fileType.indexOf("image") < 0 ? false : true;
}
/**
* 解析文件字节数
* @param {[type]} bytes 总字节数
* @param {[type]} decimal 小数点后位数
* @return {[type]} 解析后的文件大小
*/
function parseBytes(bytes, decimal) {
var fileSize = 0,
units = ["KB", "MB", "GB", "TB"];
decimal = decimal || 3;
for (var i = 0, size = bytes / 1024; size > 1; size /= 1024, i++) {
fileSize = size.toFixed(decimal) + units[i];
}
return fileSize;
}
// 格式化时间显示,如"2月6日 13:01"
function formatTime(time) {
var month, day, hour, minute;
time = new Date(time);
month = time.getMonth() + 1;
day = time.getDate();
hour = time.getHours();
minute = time.getMinutes();
minute < 10 && (minute = "0" + minute);
return month + "月" + day + "日 " + hour + ":" + minute;
}
// 格式化时间显示,如"2017.02.07 19:01"
function formatDate(time) {
var year, month, day, hour, minute;
time = new Date(time);
year = time.getFullYear();
month = time.getMonth() + 1;
day = time.getDate();
hour = time.getHours();
minute = time.getMinutes();
// 若为个位数,则在前加“0”
month < 10 && (month = "0" + month);
day < 10 && (day = "0" + day);
hour < 10 && (hour = "0" + hour);
minute < 10 && (minute = "0" + minute);
return year+"."+month + "." + day + " " + hour + ":" + minute;
}
// window resize和scroll事件的基本优化
var resizeTimer = null;
$(window).resize(function() {
(resizeTimer) && clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
console.info("resize触发了!");
}, 100);
});