//全局事件
var _ua = navigator.userAgent.toLowerCase();
//当前环境
var env = (function(){
return !/mobile|android/.test(_ua)?"pc":_ua.indexOf("micromessenger")>-1?"weixin":/qq\/([\d\.]+)*/.test(_ua)||/qzone\//.test(_ua)?"qq":/jzyc\/\d\.\d/.test(_ua)?"jzyc":"mobile";
})();
//数组去重
function arrayUniq(array) {
return Array.prototype.filter.call(array, function(item, idx){ return item && array.indexOf(item) == idx; });
}
function arrayUniq(arr){
var returnArr=[];
for (var i=0,len=arr.length;i<len;i++){
((","+returnArr+",").indexOf(","+arr[i]+",")<0)?returnArr.push(arr[i]):'';
};
return returnArr;
}
//去重合并数组
function mergeArray(a, b) {
for (var i = 0; i < b.length; i++) {
(("," + a + ",").indexOf("," + b[i] + ",") < 0) && a.push(b[i]);
}
return a;
}
//字符串长度
function strLenGB(str){
var realLen = str.length;
for (var i = 0; i <str.length; i++) {
if(str.charCodeAt(i) > 255) realLen++ ;
}
return realLen;
}
function strLenGB(str){
return str.replace(/[\u00FF-\uFFFF]/g," ").length;
}
//进行字符长度验证,如果超过长度则返回截断后的字符串
function strSubGB(str,start,len,flag){
var total = strLenGB(str);
if(total > (len-start)){
var flag=flag||"";
var strTemp=str.replace(/[\u00FF-\uFFFF]/g, "@-").substr(start,len);
var subLen =strTemp.match(/@-/g)?strTemp.match(/@-/g).length:0;
return str.substring(0,len-subLen)+flag;
}
return str;
}
//获取url参数
function getQuery(name, url) {
var u = arguments[1] || window.location.search,
reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"),
r = u.substr(u.indexOf("\?") + 1).match(reg);
return r != null ? r[2] : "";
}
//添加url参数
function setQuery(json, url){
var hash = url ? url.match(/#.*/)&&url.match(/#.*/)[0]||"" : location.hash,
search = url ? url.replace(/#.*/,"").match(/\?.*/)&&url.replace(/#.*/,"").match(/\?.*/)[0]||"" : location.search,
path = url ? url.replace(/#.*/,"").replace(/\?.*/,"") : location.protocol+"//"+location.host+location.pathname;
for(var i in json){
var query = i+"="+json[i],
oldValue = getQuery(i, search);
if(oldValue){
search = search.replace(i+"="+oldValue,i+"="+json[i]);
}else{
search = (search.length>0)?search +"&"+ query:"?"+query;
}
}
return path+search+hash;
}
//获取指定hash值 #key=xx
function getHash(name) {
var u = arguments[1] || location.hash;
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = u.substr(u.indexOf("#") + 1).match(reg);
if (r != null) {
return r[2];
}
return "";
}
function htmlDecode(str){
return typeof(str) != "string" ? "" : str.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, "\"").replace(/ /g, " ").replace(/'/g,"'").replace(/&/g, "&");
}
function htmlEncode(str){
return typeof(str) != "string" ? "" : str.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/\"/g, """).replace(/\'/g, "'").replace(/ /g, " ");
}
// 清除缓存记录
function removeStorage(key) {
window.localStorage.removeItem(key);
}
/**
* 保存本地缓存信息
* @param key 保存的key
* @param value 需要保存的值
* @param isJson 是否是json格式数据
*/
function saveStorage(key, value, isJson) {
window.localStorage.setItem(key, isJson ? JSON.stringify(value) : value);
}
/**
* 通过key获取对应的值
* @param key
* @return {*}
*/
function getStorage(key) {
return window.localStorage.getItem(key);
}
// 判断是否支持本地缓存
function isSupportStorage() {
if (!window.localStorage) {
return false;
}
//safari的隐私模式不支持缓存
try {
window.localStorage.setItem("test", true);
window.localStorage.removeItem("test");
return true;
} catch(e) {
return false;
}
}
function isDate(d) {
try {
var d = new Date(d);
d = null;
return true;
} catch (e) {
return false;
}
}
function format(s) {
var re = /{\d+}/g,
args = Array.prototype.slice.call(arguments, 1),
r = s.toString();
return r.replace(re, function(v) {
var vi = v.substr(1, v.length - 2);
return typeof args[vi] === 'undefined' ? v : args[vi];
});
}
//读取cookie
function getCookie(name) {
var reg = new RegExp("(^| )" + name + "(?:=([^;]*))?(;|$)"), val = document.cookie.match(reg);
return val ? (val[2] ? unescape(val[2]).replace(/(^")|("$)/g,"") : "") : null;
}
//写入cookie
function setCookie(name, value, expires, path, domain, secure) {
var exp = new Date(), expires = arguments[2] || null, path = arguments[3] || "/", domain = arguments[4] || null, secure = arguments[5] || false;
expires ? exp.setMinutes(exp.getMinutes() + parseInt(expires)) : "";
document.cookie = name + '=' + escape(value) + ( expires ? ';expires=' + exp.toGMTString() : '') + ( path ? ';path=' + path : '') + ( domain ? ';domain=' + domain : '') + ( secure ? ';secure' : '');
}
//交换赋值
//获取服务器时间
var getServerTime = function(url) {
var xhr = $xhrMaker(),
var url = url || location.protocol+"//" + window.location.hostname+"/favicon.ico";
try{
xhr.open("HEAD", url, false);
xhr.send();
}catch(e){
return new Date();
}
return new Date(xhr.getResponseHeader("Date"));
function $xhrMaker(){
var xhr;
try{// Firefox, Opera 8.0+, Safari
xhr=new XMLHttpRequest();
}catch(e){//Internet Explorer
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try {
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
xhr=null;
}
}
};
return xhr;
}
}
//日期格式
var format = function(date,formatStr){
var arrWeek=['日','一','二','三','四','五','六'];
var str=formatStr
.replace(/yyyy/i,date.getFullYear())
.replace(/yy/i,$addZero(date.getFullYear() % 100,2) )
.replace(/mm/i,$addZero(date.getMonth()+1,2))
.replace(/m/ig,date.getMonth()+1)
.replace(/dd/i,$addZero(date.getDate(),2) )
.replace(/d/ig,date.getDate())
.replace(/hh/i,$addZero(date.getHours(),2))
.replace(/h/ig,date.getHours())
.replace(/ii/i,$addZero(date.getMinutes(),2))
.replace(/i/ig,date.getMinutes())
.replace(/ss/i,$addZero(date.getSeconds(),2))
.replace(/s/ig,date.getSeconds())
.replace(/w/ig,date.getDay())
.replace(/W/g,arrWeek[date.getDay()]);
return str;
function $addZero(v,size){
for(var i=0,len=size-(v+"").length;i<len;i++){
v="0"+v;
};
return v+"";
}
}
//时间间隔差 类似倒计时
var getTimeDistance = function (ts){
var timeLeft = [0,0,0,0];
timeLeft[0] = (ts>86400) ? parseInt(ts/86400):0;
ts = ts - timeLeft[0] * 86400;
timeLeft[1] = (ts>3600)?parseInt(ts/3600):0;
ts = ts - timeLeft[1] * 3600;
timeLeft[2] = (ts>60)?parseInt(ts/60):0;
timeLeft[3] = ts - timeLeft[2] * 60;
return timeLeft;
}
var getTimeInterval = function (st,et){
var timeLeft=[0,0,0,0];
var timeStr="";
var ts=(et>st)?parseInt((et-st)/1000):0;
timeLeft[0]=(ts>86400)?parseInt(ts/86400):0;
ts=ts - timeLeft[0] * 86400;
timeLeft[1]=(ts>3600)?parseInt(ts/3600):0;
ts=ts - timeLeft[1] * 3600;
timeLeft[2]=(ts>60)?parseInt(ts/60):0;
timeLeft[3]=ts - timeLeft[2] * 60;
timeStr=(timeLeft[0]>0)?timeLeft[0]+"天":"";
timeStr+=(timeLeft[0]<=0 && timeLeft[1]<=0)?"":(timeLeft[1]+"小时");
timeStr+=(timeLeft[0]<=0 && timeLeft[1]<=0 && timeLeft[2]<=0)?"":(timeLeft[2]+"分钟");
timeStr+=(timeLeft[0]<=0 && timeLeft[1]<=0 && timeLeft[2]<=0 && timeLeft[3]<=0)?"":timeLeft[3]+"秒";
return timeStr;
}
//合并对象
function mergeObject(a,b){
for(var prop in b){
if(!b.hasOwnProperty(prop)){
return;
}
if(!a[prop]){
a[prop] = b[prop];
}else if(Object.prototype.toString.call(b[prop] == "[object object]")){
mergeObject(a[prop],b[prop]);
}else{
a[prop] = b[prop];
}
}
return a;
}
//对象类型判断 isType("String", obj)
function isType(type, obj) {
return Object.prototype.toString.call(obj) === "[object " + type + "]"
}
//js 字符串截取空白的trim的原型方法
String.prototype.trim = function(){
return this.replace(/(^\s*)|(\s*$)/g,'');
}
//滑动
var _topTimer = null;
window.goTop = function(top ,acceleration, time) {
if(_topTimer)clearTimeout(_topTimer);
top = Math.floor(top);
acceleration = acceleration || 0.1;
time = time || 16;
var y1 = 0;
var y2 = 0;
var y3 = 0;
if (document.documentElement) {
y1 = document.documentElement.scrollTop || 0;
}
if (document.body) {
y2 = document.body.scrollTop || 0;
}
var y3 = window.scrollY || 0;
// 滚动条到页面顶部的垂直距离
var y = Math.max(y1, Math.max(y2, y3));
console.log("top:" + y);
// 滚动距离 = 目前距离 / 速度, 因为距离原来越小, 速度是大于 1 的数, 所以滚动距离会越来越小
var speed = 1 + acceleration;
window.scrollTo(0, top - y > 0 ? ((top + (1 / acceleration) - y) * (speed - 1) + y) : (top + (y - top) / speed));
// 如果距离不为零, 继续调用迭代本函数
if (y < $("body").height() - $(window).height() && (top - y > 0) || (top - y < 0 && y - top > 0)) {
_topTimer = setTimeout(function(){
goTop(top,acceleration,time);
}, time);
}
}
function $shuffle(arr) {
var array = arr.concat();
for(var j, x, i = array.length; i; j = parseInt(Math.random() * i), x = array[--i], array[i] = array[j], array[j] = x);
return array;
}
//发送请求
function sendJs(url,opt) {
var option={
onLoad:null,//成功时回调函数
onError:null,//加载错误时回调函数
onTimeout:null,//超时时回调函数
timeout:8000,//超时时间
charset:"utf-8"//默认字符集
};
if(arguments.length==1){
if(typeof arguments[0]=="object"){//只有一个参数,且参数为json对象的情况
opt=arguments[0];
url=opt.url;
}else{//只有一个参数,且参数字符串(url地址)的情况
opt={};
}
}
/*增加键值对data参数支持*/
if(typeof(opt.data)=='object'){
var param=[];
for(var k in opt.data){param.push(k+'='+opt.data[k])}
if(param.length>0){
param=param.join('&');
url+=(url.indexOf('?')>0?'&':'?')+param;
}
}
/*增加键值对data参数支持*/
for(var i in opt){
if(opt.hasOwnProperty(i)){
option[i]=opt[i];
}
}
var el=document.createElement("script");
el.charset=option.charset||"utf-8";
el.onload = el.onreadystatechange = function() {
if(/loaded|complete/i.test(this.readyState) || navigator.userAgent.toLowerCase().indexOf("msie") == -1) {
option.onLoad&&option.onLoad();//加载成功之后的回调
clear();
}
};
el.onerror = function(){
option.onError&&option.onError();//加载错误时的回调
clear();
};
el.src = url;
document.getElementsByTagName('head')[0].appendChild(el);
if (typeof option.onTimeout=="function") {
setTimeout(function(){
option.onTimeout();
},option.timeout);
};
var clear = function(){
if(!el){return ;}
el.onload = el.onreadystatechange = el.onerror = null;
el.parentNode&&(el.parentNode.removeChild(el));
el = null;
}
};
//读取COOKIE
function $getCookie(name) {
var reg = new RegExp("(^| )" + name + "(?:=([^;]*))?(;|$)"), val = document.cookie.match(reg);
return val ? (val[2] ? unescape(val[2]) : "") : null;
}
//删除cookie
function $delCookie(name, path, domain, secure) {
var value = $getCookie(name);
if(value != null) {
var exp = new Date();
exp.setMinutes(exp.getMinutes() - 1000);
path = path || "/";
document.cookie = name + '=;expires=' + exp.toGMTString() + ( path ? ';path=' + path : '') + ( domain ? ';domain=' + domain : '') + ( secure ? ';secure' : '');
}
}
//写入COOKIES
function $setCookie(name, value, expires, path, domain, secure) {
var exp = new Date(), expires = arguments[2] || null, path = arguments[3] || "/", domain = arguments[4] || null, secure = arguments[5] || false;
expires ? exp.setMinutes(exp.getMinutes() + parseInt(expires)) : "";
document.cookie = name + '=' + escape(value) + ( expires ? ';expires=' + exp.toGMTString() : '') + ( path ? ';path=' + path : '') + ( domain ? ';domain=' + domain : '') + ( secure ? ';secure' : '');
}
function $xss(str,type){
//空过滤
if(!str){
return str===0 ? "0" : "";
}
switch(type){
case "none": //过度方案
return str+"";
break;
case "html": //过滤html字符串中的XSS
return str.replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function(r){
return "&#" + r.charCodeAt(0) + ";"
}).replace(/ /g, " ").replace(/\r\n/g, "<br />").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
break;
case "htmlEp": //过滤DOM节点属性中的XSS
return str.replace(/[&'"<>\/\\\-\x00-\x1f\x80-\xff]/g, function(r){
return "&#" + r.charCodeAt(0) + ";"
});
break;
case "url": //过滤url
return escape(str).replace(/\+/g, "%2B");
break;
case "miniUrl":
return str.replace(/%/g, "%25");
break;
case "script":
return str.replace(/[\\"']/g, function(r){
return "\\" + r;
}).replace(/%/g, "\\x25").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\x01/g, "\\x01");
break;
case "reg":
return str.replace(/[\\\^\$\*\+\?\{\}\.\(\)\[\]]/g, function(a){
return "\\" + a;
});
break;
default:
return escape(str).replace(/[&'"<>\/\\\-\x00-\x09\x0b-\x0c\x1f\x80-\xff]/g, function(r){
return "&#" + r.charCodeAt(0) + ";"
}).replace(/ /g, " ").replace(/\r\n/g, "<br />").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
break;
}
}
function $md5(){
// md5加密
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
var option={};
option.hexcase=hexcase;
option.b64pad=b64pad;
option.chrsz=chrsz;
option.hex_md5=hex_md5;
option.binl2hex=binl2hex;
option.core_md5=core_md5;
return option;
function hex_md5(s){
return binl2hex(core_md5(str2binl(s), s.length * option.chrsz));
}
function binl2hex(binarray){
var hex_tab = option.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
function core_md5(x, len){
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16){
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
function md5_cmn(q, a, b, x, s, t){
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t){
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t){
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t){
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t){
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function safe_add(x, y){
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
function bit_rol(num, cnt){
return (num << cnt) | (num >>> (32 - cnt));
}
function str2binl(str){
var bin = Array();
var mask = (1 << option.chrsz) - 1;
for(var i = 0; i < str.length * option.chrsz; i += option.chrsz)
bin[i>>5] |= (str.charCodeAt(i / option.chrsz) & mask) << (i%32);
return bin;
}
}
//var m=$md5();
//var code=m.hex_md5('abc');
function $extend(){
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, options;
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target != "object" && typeof target != "function" )
target = {};
for ( ; i < length; i++ )
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null )
// Extend the base object
for ( var name in options ) {
var copy = options[ name ];
// Prevent never-ending loop
if ( target === copy )
continue;
if ( copy !== undefined )
target[ name ] = copy;
}
// Return the modified object
return target;
}
常用js函数
最新推荐文章于 2022-12-12 20:15:56 发布