JavaScript基础工具类库
作者:陆金龙
发表时间:2014-10-07 19:40
//*
* js基础工具类库:处理url 数值 时间格式 文件长度格式 json对象转换等
* 整理:陆金龙
* 联系方式:kinglong1984@126.com
* 制作日期:2014-10-07
//*
* 获得url中的参数值
* @method
* @param {string} name 参数名
* @return {string} 没有该参数时返回null
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null)
return decodeURIComponent(r[2]);
return null;
}
//*
* 阻止事件冒泡
* @param {event} e 参数名
function stopBubble(e) {
//一般用在鼠标或键盘事件上
if (e && e.stopPropagation) {
//W3C取消冒泡事件
e.stopPropagation();
} else {
//IE取消冒泡事件
window.event.cancelBubble = true;
}
}
//*
* 获得浏览器
* @return {string} 浏览器名称
function getBlowser() {
var blws = '';
var ua = navigator.userAgent.toLowerCase();
if (window.ActiveXObject)
blws = 'ie';
else if (document.getBoxObjectFor)
blws = 'firefox';
else if (window.MessageEvent && !document.getBoxObjectFor)
blws = 'chrome';
else if (window.opera)
blws = 'opera';
else if (window.openDatabase)
blws = 'safari';
return blws;
}
//*
* 禁用F5刷新
* @method
function DisableF5() {
document.onkeydown = function () {
with (event) {
if (keyCode == 116) {
event.keyCode = 0;
event.cancelBubble = true;
return false;
}
}
}
}
//*
* 睡眠多少毫秒
* @method
* @param {Number} milliSeconds 毫秒数
function sleep(milliSeconds) {
var start = new Date().getTime();
while (true) {
if (new Date().getTime() - start > milliSeconds)
break;
};
}
//========
//Json对象转换处理
//========
//*
* 字符串转为json jQuery.parseJSON(strJson)
//*
* JSON转换为字符串
* @method
* @param {JSON} Json json对象或数组
* @return {string} 转换后的字符串
* @remark 注意 IE低版本下不支持
function JSONstringify(Json) {
try {
//if ($.browser.msie) {
// if ($.browser.version == "7.0" || $.browser.version == "6.0") {
// var result = JSON.stringify(Json);//错误
// }
//}
var result = JSON.stringify(Json);
} catch (e) {
alert('您的浏览器版本不支持json对象的转换,请升级浏览器!');
result = "";
}
return result;
}
//========
//数字处理
//========
//*
* 数字进制转换
* @param {Number} num 数值或字符串
* @param {Number} from 原始进制
* @param {Number} to 目标进制
* @return {string} 转换结果
function changeNumFormt(num, from, to) {
var res;
try {
res = parseInt(num, from).toString(to);
}
catch (e) {
res = "error";
}
return res;
}
//*
* 将浮点数四舍五入,取小数点后2位,不足2位则补0
* @return 返回的是字符串的格式
* @remark 等效于直接使用(x).toFixed(2)
function toDecimal(x) {
try {
var f_x = parseFloat(x);
var f_x = Math.round(x * 100) / 100;//Math.round返回4舍5入的整数
var s_x = f_x.toString();
var pos_decimal = s_x.indexOf('.');
if (pos_decimal < 0) {
pos_decimal = s_x.length;
s_x += '.';
}
while (s_x.length <= pos_decimal + 2) {
s_x += '0';
}
return s_x;
} catch (e) {
alert('function:changeTwoDecimal->parameter error');
return false;
}
}
//=========
//时间处理
//=========
//*
* 将日起对象格式化输出
* @param {Date} date 时间对象
* @param {String} format 如yyyy-MM-dd HH:mm:ss.fff 或 yyyy年MM月dd日 HH:mm 或 yyyy/MM/dd
* @return {String} 格式化的的时间
function getFormatDate(date, format) {
try {
format = format.replace("yyyy", date.getFullYear());
var month = date.getMonth() + 1;
if (month < 10) {
month = '0' + month;
}
format = format.replace("MM", month);
format = format.replace("dd", date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
format = format.replace("HH", date.getDate() < 10 ? '0' + date.getHours() : date.getHours());
format = format.replace("mm", date.getDate() < 10 ? '0' + date.getMinutes() : date.getMinutes());
format = format.replace("ss", date.getDate() < 10 ? '0' + date.getSeconds() : date.getSeconds());
var ms = date.getMilliseconds();
if (ms < 10) {
ms = '00' + ms;
}
else if (ms < 100) {
ms = '0' + ms;
}
format = format.replace("fff", ms);
return format;
} catch (e) {
alert("getFormatDate->parameter error");
return "";
}
}
//*
* 将年、月、日转为日期格式
* @param {Number} year 年份
* @param {Number} month 月份
* @param {Number} day 日
* @param {String} split 分隔符
* @return {String} 格式化的日期,如20140513 ,2014-05-13,2014/05/13等
function getFormatDateFromYearMonthDay(year, month, day, split) {
if (split == null) {
split = "";
}
if (month < 10) {
month = "0" + month;
}
if (day < 10) {
day = "0" + day;
}
var formatTime = "" + year + split + month + split + day;
return formatTime;
}
//*
* 将json时间转为日期格式
* @param {String} time json对象中格式以毫秒为单位表示的日期和时间
* @param {String} split 分隔符
* @return {String} 格式化的日期,如2014-05-13,2014/05/13等
function getFormatDateFromJson(time, split) {
if (time != null) {
var date = new Date(parseInt(time.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1;
return date.getDate(date.getFullYear(), date.getMonth() + 1, date.getDate(), split);
}
return "";
}
//*
* 将json时间转为中文日期
* @param {String} time json日期格式 以 1 毫秒为单位表示的日期和时间
* @return {String} 中文日期格式,如:2014年05月13日
function getCNDateFromJson(time) {
if (time != null) {
var date = new Date(parseInt(time.replace("/Date(", "").replace(")/", ""), 10));
return getFormatDate(date, "yyyy年MM月dd日");
}
return "";
}
//*
* 计算两个时间值的差
* @param {String} interval 计算类型:D是按照天、H是按照小时、M是按照分钟、S是按照秒、T是按照毫秒
* @param {Date} date1 起始日期 格式为年月格式 为2012-06-20 或 2009-06-22 14:22:53
* @param {Date} date2 结束日期
* @return {String} 时间差
function getTimeDiff(interval, date1, date2) {
var objInterval = { 'D': 1000 * 60 * 60 * 24, 'H': 1000 * 60 * 60, 'M': 1000 * 60, 'S': 1000, 'T': 1 };
interval = interval.toUpperCase();
var dt1 = Date.parse(date1.replace(/-/g, "/"));
var dt2 = Date.parse(date2.replace(/-/g, "/"));
try {
return ((dt2 - dt1) / objInterval[interval]).toFixed(2); //保留两位小数点
} catch (e) {
return e.message;
}
}
//*
* 根据到期时间计算剩余时间
* @param {String} strdate 到期时间(json对象中的日期格式)
* @return {String} 剩余时间
function getExpiredDate(strdate) {
var str = parseInt(strdate.replace("/Date(", "").replace(")/", ""), 10);
var date = new Date(str);
var dateNow = new Date();
var dateDiff = date.getTime() - dateNow.getTime(); //时间差的毫秒数
var days = Math.floor(dateDiff / (24 * 3600 * 1000)); //计算出相差天数
var hours = Math.floor(dateDiff / (3600 * 1000));
var minutes = Math.floor(dateDiff / (60 * 1000));
if (days > 0) {
return days + "天";
}
else if (hours > 0) {
return hours + "小时";
}
else if (minutes > 0) {
return minutes + "分钟";
}
else {
return "已到期";
}
}
//=========
//文件处理
//=========
//*
* 根据文件大小获取大小显示
* @param {Number} fileLength 以Byte计算的文件内容长度
* @return {String} 显示的文件长度和单位
function getFileSize(fileLength) {
var strLength;
try {
var length = parseFloat(fileLength);
var unit = "Byte";
if (length > 1024) {
length = length / 1024;
unit = "KB";
if (length > 1024) {
length = length / 1024;
unit = "MB";
if (length > 1024) {
length = length / 1024;
unit = "GB";
}
strLength = Math.round(length * 100) / 100
strLength = strLength + unit;
}//MB GB 两位小数
else {
strLength = Math.round(length ) + unit;
}//KB 整数
}
else {
strLength = Math.round(length) + unit;
}//Byte 整数
return strLength;
}
catch (Exception) {
return "";
}
}
//*
* 根据文件扩展名获取图标名
* @param {String} ext 文件扩展名
function getExtImgName(ext) {
var res;
switch (ext) {
case "doc":
case "docx":
res = "word";
break;
case "xls":
case "xlsx":
res = "excel";
break;
case "ppt":
res = "ppt";
break;
case "pdf":
res = "pdf";
break;
case "png":
case "jpg":
case "gif":
res = "pic";
break;
default:
res = "default";
break;
}
return res;
}
//=========
//图片处理
//=========
//*
* 图片旋转
* @param {String} imgId img标签的Id
* @param {Number} angle 旋转角度选项: 1 顺时针旋转90度,2,顺时针旋转180度,3 逆时针旋转90度
var num = 0;
function rotateImg(imgId, angle) {
var blws = getBlowser();
num = (num + angle) % 4;
if (blws == 'ie') {
document.getElementById(imgId).style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=' + num + ')';
}
else if (blws == 'chrome') {
$("#" + imgId).rotate(90 * num);
}
else {
}
}
//*
* 注册图片缩放
* @param {String} img所在Div的Id
function registerEventForImg(imgDivId) {
$("#" + imgDivId).bind("mousewheel", function () {
if (event.wheelDelta > 0) {
imgToSize(10);
} else {
imgToSize(-10);
}
});
}
//*
* 图片缩放
* @param {String} imgId img标签的Id
* @param {Number} size 放缩百分比
function imgToSize(imgId,size) {
var img = $("#" + imgId);
var oWidth = img.width(); //取得图片的实际宽度
var oHeight = img.height(); //取得图片的实际高度
if (blws == 'ie' && (num % 2 != 0)) { //处理ie下旋转引起的变化
oWidth = img.height();
oHeight = img.width();
}
if (oWidth > 100 || size > 0) { //防止无限缩小,限制最小宽度为100px
img.width(oWidth + parseInt(oWidth * size / 100));
img.height(oHeight + parseInt(oHeight * size / 100));
}
}