/**
* ========================14.功能函数操作 s========================
*/
var funcUtil = {
/**
* ========================判断数据类型 s========================
*/
typeOfDataUtil = {
/**
* typeof:用以获取一个变量或者表达式的类型
返回结果: 正则表达式是对象类型
number,boolean,string,function(函数),object(NULL,数组,对象),undefined
===========用于获取除object外简单的数据类型
* @param param
* @returns {"undefined"|"object"|"boolean"|"number"|"string"|"function"|"symbol"|"bigint"}
*/
"typeof" : function(param){
return typeof(param); //返回数据类型
},
/**
* instanceof: 用于判断一个变量是否某个对象的实例
Instanceof 对象数据类型:
"Boolean Number String Function Array Date RegExp Object Error"
===========用于判断A是否是B对象的实例(用于判断对象)
* @param param
* @param typeOfData
* @returns {boolean}
*/
"instanceof" : function(param,typeOfData){
return param instanceof typeOfData; //返回true或者false
},
/**
* Object.prototype.toString.call(param):
"Boolean Number String Function Array Date RegExp Object Error"
============用于获取object对象具体的数据类型
* @param param
* @returns {string}
*/
"objectDataType" : function(param){
return Object.prototype.toString.call(param); //返回对象的数据类型
}
},
/**
* ========================判断数据类型 e========================
*/
/**
* sessionStorage 操作
* @param key
* @param value
* @returns {string}
*/
"sessSet" : function(key,value){
var argLen = arguments.length;
if (argLen==1) { //取值
return window.sessionStorage.getItem(key);
}else{ //存值
window.sessionStorage.setItem(key,value);
}
},
"sessClear" : function(key){
var argLen = arguments.length;
if (argLen == 0) { //清除所有
window.sessionStorage.clear();
}else{
window.sessionStorage.removeItem(key);
}
},
/**
* localStorage 操作
* @param key //key,value都入参,即设置;只有key入参,即获取
* @param value
* @returns {string}
*/
"localSet" : function(key,value){
var argLen = arguments.length;
if (argLen==1) { //获取
return window.localStorage.getItem(key);
}else{
window.localStorage.setItem(key,value);
}
},
/**
* 清除本地缓存
* @param key //可填,key入参,即清除该key;key不入参,即清除所有
*/
"localClear" : function(key){
var argLen = arguments.length;
if (argLen == 0) { //清除所有
window.localStorage.clear();
}else{
window.localStorage.removeItem(key);
}
},
/**
* cookie 操作--设置过期时间
* @param days //可填,设置过期天数(默认当天过期)
* @returns {Date}
*/
"getexpire" : function(days){
var Dt = new Date();
var year = Dt.getFullYear();
var month = parseInt(Dt.getMonth())+1;
var day = Dt.getDate();
day += days&&days>0?days-1:0;
var TDt = new Date(year,month,day,23,59,59);
return TDt;
},
"setCookie" : function(c_name,value,expiredays){
document.cookie=c_name+ "=" +escape(value) + ((!expiredays) ? "" : ";expires="+(this.getexpire(expiredays)).toGMTString());
},
"getCookie" : function(c_name){
if (document.cookie.length>0){
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1){
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
},
/**
* 设置页面标题兼容ios
* @param title //标题字符串
*/
"setDocumentTitle" : function(title){
var $body = $('body');
document.title = title;
var $iframe = $("<iframe style='display:none;' src='../resources/images/favicon.ico'></iframe>");
$iframe.on('load',function() {
setTimeout(function() {
$iframe.off('load').remove();
}, 0);
}).appendTo($body);
},
"setDocumentTitleJS" : function(title){
document.title = title;
var iframe = document.createElement("iframe");
iframe.id = "iframe";
iframe.src = "../images/favicon.ico";
iframe.style.cssText = "display:none";
iframe.addEventListener("load",function(){
document.body.appendChild(iframe);
setTimeout(function() {
iframe.removeEventListener('load');
iframe.parentNode().removeChild(document.getElementById("iframe"));
}, 0);
})
},
/**
* 判断是否滚动到底部:
* @param elem //滚动节点元素
* @param callback //滚动到底部回调函数
*/
"setScroll" : function (elem,callback){
document.addEventListener("scroll",function(){
var listElem = elem,
clientHeight = document.documentElement.clientHeight,
scrollTop = document.documentElement.scrollTop || document.body.scrollTop,
scrollHeight = listElem.scrollHeight,
offsetTop = listElem.offsetTop;
if ((clientHeight+scrollTop) >= (scrollHeight+offsetTop)) {
console.log("滚动到底部");
callback();
}
},false);
},
/**
* 功能: 验证码发送倒计时
* @param codeElem //验证码节点元素
* @param activeClass //验证码非置灰类名
* @param disabledClass //验证码置灰类名
*/
"setTimer" : function(codeElem,activeClass,disabledClass){
var _this = this;
_this.setBtnDisable(codeElem,true,activeClass);
var time = 60;
var interval = setInterval(function(){
if(time >=0){
if(time < 10){
time = "0" + time;
}
var str = time+"秒后重新发送";
codeElem.innerHTML = str;
time --;
}else{
clearInterval(interval);
codeElem.innerHTML = "重新获取";
_this.setBtnDisable(codeElem,false,activeClass);
}
}, 1000);
},
/**
* 功能: 设置按钮颜色及是否可点击
* @param codeElem //验证码节点元素
* @param flag //是否置灰标志
* @param activeClass //验证码非置灰类名
* @param disabledClass //验证码置灰类名
*/
"setBtnDisable" : function(codeElem,flag,activeClass,disabledClass){
if(flag){
codeElem.className = codeElem.className.replace(activeClass,disabledClass);
codeElem.disabled = true;
}else{
codeElem.className = codeElem.className.replace(disabledClass,activeClass);
codeElem.disabled = false;
}
},
/**
* 动态引入js文件,后缀加上时间,避免缓存---只适用于get请求
*/
"clearCache" : function(){
// avoid caching
(function(){
function load(scripts){
scripts.split(' ').forEach(function(script){
document.write('<script src="../src/'+script+'.js?'+(+new Date)+'"></scr'+'ipt>')
})
}
load('zepto event ie')
})()
},
/**
* 判断是否为空
* @param value
* @returns {boolean}
*/
"isDefine" : function(value){
if(value == null || value == "" || value == "undefined" || value == undefined || value == "null" || value == "(null)" || value == 'NULL' || typeof(value) == 'undefined'){
return false;
}
else{
value = value+"";
value = value.replace(/\s/g,"");
if(value == ""){
return false;
}
return true;
}
},
/**
* 搜索关键字高亮显示
* @param str //现有字符串
* @param keyword //搜索关键字
* @returns {*}
*/
"setHighlight" : function (str,keyword){
var newstr = str;
if(trim(keyword)=="") return newstr;
var temp=str;
var htmlReg = new RegExp("\<.*?\>","i");
var arrA = new Array();
//替换HTML标签
for(var i=0;true;i++)
{
var m=htmlReg.exec(temp);
if(m){
arrA[i]=m;
}else{
break;
}
temp=temp.replace(m,"{[("+i+")]}");
}
words = unescape(keyword.replace(/\+/g,' ')).split(/\s+/);
//替换关键字
for (w=0;w<words.length;w++)
{
var r = new RegExp("("+words[w].replace(/[(){}.+*?^$|\\\[\]]/g, "\\$&")+")","ig");
temp = temp.replace(r,"<b style='color:#2dc16c;'>$1</b>");
}
//恢复HTML标签
for(var i=0;i<arrA.length;i++)
{
temp=temp.replace("{[("+i+")]}",arrA[i]);
}
newstr=temp;
return newstr;
},
/**
* 特殊字符处理
* @param str
* @returns {string}
*/
"setSpecial" : function(str){
//var pattern = /[`~!@#\$%\^\&\*\(\)_\+<>\=\s\-\?:"\{\},\.\\\/;'\[\]]/im;
var pattern = /[`~!!@#\¥\……\$%\^\&\*\(\)\——\·\(\)_\+<>\=\-\?:"\{\},\.\\\/;'\[\]]/im;
var rs = "";
for (var i=0; i<str.length; i++){
rs += str.substr(i, 1).replace(pattern, '');
}
return rs;
},
/**
* js过滤emoji表情
* @param emojireg
* @returns {*}
*/
"filterEmoji" : function(emojireg){
var ranges = [
'\ud83c[\udf00-\udfff]',
'\ud83d[\udc00-\ude4f]',
'\ud83d[\ude80-\udeff]'
];
emojireg = emojireg .replace(new RegExp(ranges.join('|'), 'g'), '');
return emojireg;
}
/**
* html转义:html标签转换成对应字符串
* @param getValue
* @returns {*|string}
*/
"setOutHTML": function(getValue) {
var endValue=getValue;
if(typeof(getValue)=="string"){
endValue=((getValue.replace(/<(.+?)>/gi,"<$1>")).replace(/ /gi," ")).replace(/\n/gi,"<br>");
}
return endValue;
},
/**
* 字符串: js去掉html标签和去掉字符串文本的所有的空格(过滤html标签和空格)
* @param str
* @returns {void | string | never | *}
*/
"delHtmlTag": function(str){
return str.replace(/<[^>]+>/g,""); //去掉所有的html标记
},
/**
* textarea多文本输入框: 输入换行等处理
IE9以上、FF、chrome的换行为\n, IE7-8的时候换行为\r\n,空格都为\s
注:如果使用jQuery的val()获取textarea的值,取得的值是不含有回车(\r)字符的.
* @param strValue
* @returns {string}
*/
"textareaBr": function(strValue){
return strValue.replace(/\r\n/g, '<br/>').replace(/\n/g, '<br/>').replace(/\s/g, ' ');
},
/**
* 将图片src转化为base 64
* @param sourceElem //源图片节点或图片路径
* @param objElem //目标图片节点
* eg : createImgData("test.png",document.getElementById("imgcanvas"));
*/
"createImgData" : function(sourceElem,objElem) {
var image = new Image();
image.src = sourceElem.src || sourceElem;
image.onload = function(){
var tmpCanvas = document.createElement("canvas");
var tmpCtx = tmpCanvas.getContext("2d");
tmpCanvas.width = image.width;
tmpCanvas.height = image.height;
tmpCtx.drawImage(image, 0, 0);
var base64Url = tmpCanvas.toDataURL();
objElem.src = base64Url;
};
image.onerror = function(){
alert("图片预加载失败");
};
},
/**
* 图片&音频预加载:
* @param imgPath //文件夹路径
* @param imgsArr //图片数组
* @param cb //回调函数(返回百分比进度)
* eg : preLoadMedias("../images/",["a.png","b.png","c.png"],function(percent){
console.log("当前进度:"+percent);
});
*/
"preLoadMedias" : function(imgPath,imgsArr,cb){
var ass = {img:imgsArr,vio:[]};
// $('img').each(function(index, el) {
// ass.img.push($(this).attr('src'));
// });
$('audio').each(function(index, el) {
ass.vio.push({'id':$(this).attr('id'),'src':$(this).attr('src')});
});
ass.img=ass.img.uniquelize(); //用到了tkBASE.js里的去重方法
ass.vio=ass.vio.uniquelize(); //用到了tkBASE.js里的去重方法
// ass.vio=[{'id':'aa','src':'music/aa.mp3'},{'id':'a','src':'music/a.mp3'},{'id':'b','src':'music/b.mp3'},{'id':'c','src':'music/c.mp3'},{'id':'d','src':'music/d.mp3'},{'id':'e','src':'music/e.mp3'},];
var _assets = [];
$.each(ass.img, function(index, obj) {
// _assets.push({'type':'a','src':$(new Image()).attr('src',obj).attr('src')});
var imgObjSrc = imgPath + obj;
_assets.push({'type':'a','src':imgObjSrc});
});
$.each(ass.vio, function(index, obj) {
// _assets.push({'type':'b','id':obj.id,'src':$(new Audio()).attr('src',obj.src).attr('src')});
_assets.push({'type':'b','id':obj.id,'src':obj.src});
});
var _loadMax = _assets.length;
var _loaded = 0;
if (_loadMax === 0) {
this.completeHandle();
} else {
$.each(_assets, function(index, el) {
if (el.type == 'a') {
var _img = new Image();
_img.onload = function() {
_loaded++;
console.log('a',_loaded);
var p = Math.floor(_loaded / _loadMax * 100);
cb(p);
};
_img.onerror = function() {
_loaded++;
console.log('a:error',_loaded);
var p = Math.floor(_loaded / _loadMax * 100);
cb(p);
};
_img.src = el.src;
} else {
$.ajax({
url: el.src,
type: 'GET'
})
.done(function() {
})
.fail(function() {
})
.always(function(e) {
_loaded++;
console.log("complete",_loaded);
var p = Math.floor(_loaded / _loadMax * 100);
cb(p);
});
}
});
}
},
/**
* 获取页面路径名
* @returns {string[]}
*/
"getPageName" : function(){
var a = window.location.pathname;
var b = a.split("/");
var c = b.slice(b.length-1, b.length).toString(String).split(".");
return c.slice(0, 1);
},
/**
* json转文本格式化
* @param jsonInfo
* @returns {string}
*/
"formatJsonStr" : function(jsonInfo){
var jsonStr = JSON.stringify(jsonInfo);
var nbsp = ' ';
var str = '';
var leftCount = 0;
for(var i = 0 ; i < jsonStr.length; i++){
if('{' == jsonStr[i]){
str += jsonStr[i];
leftCount++;
str += '<br>';
for(var j = 0; j < leftCount; j++){
str += nbsp;
}
}else if('}' == jsonStr[i]){
str += '<br>';
leftCount--;
for(var j = 0; j < leftCount; j++){
str += nbsp;
}
str += jsonStr[i];
}else{
str += jsonStr[i];
if(',' == jsonStr[i]){
if((i + 1) < jsonStr.length && jsonStr[i + 1] != '{'){
str += '<br>';
for(var j = 0; j < leftCount; j++){
str += nbsp;
}
}
}
}
}
return str;
},
/**
* The workhorse; converts an object to x-www-form-urlencoded serialization.
* post格式数据转成get格式数据
* @param {Object} obj
* @return {String}
* eg:
1.json数据:
var obj = {
name:"张凤",
intrestion:["ball1","ball2","ball3"],
sex:"famale",
sibings:{
brothers:[{name:"brother1",age:"12"},{name:"brother2",age:"13"}],
sisters:[{name:"sister1",age:"20"},{name:"sister2",age:"21"}]
}
};
2.json转成get格式编码:
name=%E5%BC%A0%E5%87%A4&intrestion%5B0%5D=ball1&intrestion%5B1%5D=ball2&intrestion%5B2%5D=ball3&sex=famale&sibings%5Bbrothers%5D%5B0%5D%5Bname%5D=brother1&sibings%5Bbrothers%5D%5B0%5D%5Bage%5D=12&sibings%5Bbrothers%5D%5B1%5D%5Bname%5D=brother2&sibings%5Bbrothers%5D%5B1%5D%5Bage%5D=13&sibings%5Bsisters%5D%5B0%5D%5Bname%5D=sister1&sibings%5Bsisters%5D%5B0%5D%5Bage%5D=20&sibings%5Bsisters%5D%5B1%5D%5Bname%5D=sister2&sibings%5Bsisters%5D%5B1%5D%5Bage%5D=21
3.json转成get格式编码后解码:
name=张小风&intrestion[0]=ball1&intrestion[1]=ball2&intrestion[2]=ball3&sex=famale&sibings[brothers][0][name]=brother1&sibings[brothers][0][age]=12&sibings[brothers][1][name]=brother2&sibings[brothers][1][age]=13&sibings[sisters][0][name]=sister1&sibings[sisters][0][age]=20&sibings[sisters][1][name]=sister2&sibings[sisters][1][age]=21
*/
"param" : function(obj) {
var query = '', name, value, fullSubName, subName, subValue, innerObj, i;
for(name in obj) {
value = obj[name];
if(value instanceof Array) {
for(i=0; i<value.length; ++i) {
subValue = value[i];
fullSubName = name + '[' + i + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}else if(value instanceof Object) {
for(subName in value) {
subValue = value[subName];
fullSubName = name + '[' + subName + ']';
innerObj = {};
innerObj[fullSubName] = subValue;
query += param(innerObj) + '&';
}
}else if(value !== undefined && value !== null){
query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&';
}
}
return query.length ? query.substr(0, query.length - 1) : query;
},
/**
* 计算字符串长度
* @param str //只能输入中英文,中文gbk--3个字节,utf-8 ---2个字节
* @returns {number}
*/
"countCharacters" : function(str){
var totalCount = 0;
for (var i=0; i<str.length; i++){
var c = str.charCodeAt(i);
if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <=0xff9f)){
totalCount++;
}else{
totalCount+=2;
}
}
return totalCount;
}
}
/**
* ========================14.功能函数操作 e========================
*/