kefu/static/js/functions.js

1625 lines
50 KiB
JavaScript
Raw Normal View History

2024-12-10 02:50:12 +00:00
function getBaseUrl() {
var ishttps = 'https:' == document.location.protocol ? true : false;
var url = window.location.host;
if (ishttps) {
url = 'https://' + url;
} else {
url = 'http://' + url;
}
return url;
}
function getWsBaseUrl() {
var ishttps = 'https:' == document.location.protocol ? true : false;
var url = window.location.host;
if (ishttps) {
url = 'wss://' + url;
} else {
url = 'ws://' + url;
}
return url;
}
//获取域名部分
function getDomainFromUrl(url) {
if(!url||url==""){
url=window.location.href;
}
const regex = /^https?:\/\/([^\/]+)/i;
const match = url.match(regex);
return match[1];
}
//获取协议部分
function getProtocolFromUrl(url) {
if(!url||url==""){
url=window.location.href;
}
const regex = /^(https?)/i;
const match = url.match(regex);
return match[1];
}
//获取图片链接
function getImageUrl(imgUrl,host){
var prefix=imgUrl.substr(0,4);
if(prefix=='http'){
return imgUrl;
}else{
return host+imgUrl;
}
}
function notify(title, options, callback) {
// 先检查浏览器是否支持
if (!window.Notification) {
console.log("浏览器不支持notify");
return;
}
options.body=replaceHtml(options.body);
console.log("浏览器notify权限:", Notification.permission);
// 检查用户曾经是否同意接受通知
if (Notification.permission === 'granted') {
var notification = new Notification(title, options); // 显示通知
if (notification && callback) {
notification.onclick = function(event) {
callback(notification, event);
}
setTimeout(function () {
notification.close();
},3000);
}
} else {
Notification.requestPermission().then( (permission) =>function(){
console.log("请求浏览器notify权限:", permission);
if (permission === 'granted') {
notification = new Notification(title, options); // 显示通知
if (notification && callback) {
notification.onclick = function (event) {
callback(notification, event);
}
setTimeout(function () {
notification.close();
}, 3000);
}
} else if (permission === 'default') {
console.log('用户关闭授权 可以再次请求授权');
} else {
console.log('用户拒绝授权 不能显示通知');
}
});
}
}
var titleTimer=0;
var titleNum=0;
var originTitle = document.title;
// function flashTitle() {
// if(titleTimer!=0){
// return;
// }
// titleTimer = setInterval(function(){
// titleNum++;
// if (titleNum == 3) {
// titleNum = 1;
// }
// if (titleNum == 1) {
// document.title = '【🔔】' + originTitle;
// }
// if (titleNum == 2) {
// document.title = '【★】' + originTitle;
// }
// }, 500);
//
// }
function clearFlashTitle() {
clearInterval(titleTimer);
document.title = originTitle;
}
var flashing = false;
function flashTitle() {
if (flashing) {
return;
}
flashing = true;
var originalTitle = document.title;
var intervalId;
var newTitle = "🔥✉️" + originalTitle;
function changeTitle() {
document.title = document.title == originalTitle ? newTitle : originalTitle;
}
intervalId = setInterval(changeTitle, 1000);
window.onfocus = function () {
clearInterval(intervalId);
document.title = originalTitle;
flashing = false;
};
}
function emojiGifs(){
var emojiGifs=[];
var emojiTxt = ["[a]", "[b]", "[c]", "[d]", "[e]", "[f]", "[g]", "[h]", "[i]", "[j]", "[k]", "[l]", "[m]", "[n]", "[o]", "[p]", "[q]", "[r]", "[s]", "[t]", "[u]", "[v]", "[w]", "[x]", "[y]", "[z]", "[aa]", "[bb]", "[cc]", "[dd]", "[ee]", "[ff]", "[gg]", "[hh]", "[ii]", "[jj]", "[kk]", "[ll]", "[mm]", "[nn]", "[oo]", "[pp]", "[qq]", "[rr]"];
for(var i=0;i<emojiTxt.length;i++){
emojiGifs[emojiTxt[i]]="/static/images/face/"+i+".png";
}
return emojiGifs;
}
function emojiGifsMap(){
var emojiMap=[];
var emojis=emojiGifs();
for(var key in emojis){
emojiMap.push({"name":key,"path":emojis[key]});
}
return emojiMap;
}
var faceTitles = ["[a]", "[b]", "[c]", "[d]", "[e]", "[f]", "[g]", "[h]", "[i]", "[j]", "[k]", "[l]", "[m]", "[n]", "[o]", "[p]", "[q]", "[r]", "[s]", "[t]", "[u]", "[v]", "[w]", "[x]", "[y]", "[z]", "[aa]", "[bb]", "[cc]", "[dd]", "[ee]", "[ff]", "[gg]", "[hh]", "[ii]", "[jj]", "[kk]", "[ll]", "[mm]", "[nn]", "[oo]", "[pp]", "[qq]", "[rr]", "[ss]", "[tt]", "[uu]", "[vv]", "[ww]", "[xx]", "[yy]", "[zz]", "[a1]", "[b1]", "[good]", "[NO]", "[c1]", "[d1]", "[e1]", "[f1]", "[g1]", "[h1]", "[i1]", "[g1]", "[k1]", "[l1]", "[m1]", "[n1]", "[o1]", "[p1]", "[q1]", "[cake]"];
function placeFace() {
var faces=[];
for(var i=0;i<faceTitles.length;i++){
faces[faceTitles[i]]="/static/images/face/"+i+".gif";
}
return faces;
}
function replaceContent (content,baseUrl) {// 转义聊天内容中的特殊字符
if(typeof baseUrl=="undefined"){
baseUrl="";
}
// var html = function (end) {
// return new RegExp('\\n*\\[' + (end || '') + '(pre|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\]\\n*', 'g');
// };
content = (content || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
.replace(/<(?!br).*?>/g, '') // 去掉html
//.replace(/\\n/g, '<br>') // 转义换行
content=replaceSpecialTag(content,baseUrl);
return content;
}
function replaceFace(str,baseUrl){
if(baseUrl==""){
baseUrl=getBaseUrl();
}
var faces=emojiGifs();
return str.replace(/face\[([^\s\[\]]+?)\]/g, function (face) { // 转义表情
var alt = face.replace(/^face/g, '');
return '<img width="22px" alt="' + alt + '" title="' + alt + '" src="'+baseUrl + faces[alt] + '">';
});
}
function replaceImage(str,baseUrl){
return str.replace(/img\[([^\s\[\]]+?)\]/g, function (face) { // 转义图片
var src = face.replace(/^img\[/g, '').replace(/\]/g, '');;
return '<a href="' +baseUrl+ src + '" target="_blank"><img data-src="'+baseUrl+ src +'" data-lightbox class="chatImagePic" src="' +baseUrl+ src + '?width=400"/></a>';
})
}
function replaceAudio(str){
return str.replace(/audio\[([^\s\[\]]+?)\]/g, function (face) { // 转义图片
var src = face.replace(/^audio\[/g, '').replace(/\]/g, '');;
//return '<div class="chatAudio"><audio controls ref="audio" src="'+src+'" class="audio"></audio></div>';
var html= `
<audio controls ref="audio" src="`+src+`" class="audio" style="height: 38px;"></audio>
`;
return html;
})
}
function replaceAudio2(str){
return str.replace(/audio\[(.*?)\]/g, function (result) {
var mutiFiles=result.match(/audio\[(.*?)\]/)
if (mutiFiles.length<2){
return result;
}
var html= `
<div class="voice-message">
<img src="/static/images/voice-icon2.png" class="voice-icon"/>
<span></span>
<audio src="`+mutiFiles[1]+`" controls ref="audio" ></audio>
</div>
`;
return html;
// return '<a href="'+src+'" target="_blank"/><i style="font-size: 26px;color: #606266" class="el-icon-folder-checked"></i></a>';
})
// return str.replace(/audio\[([^\s\[\]]+?)\]/g, function (face) { // 转义图片
// var src = face.replace(/^audio\[/g, '').replace(/\]/g, '');
// var html=`
// <div class="voice-message">
// <img src="/static/images/voice-icon2.png" class="voice-icon"/>
// <span></span>
// <audio src=""></audio>
// </div>
// `;
// return '<div class="chatAudio"><img width="12px" data-src="'+src+'" src="/static/images/voice-icon2.png"/></div>';
// })
}
function replaceFile(str){
return str.replace(/file\[([^\s\[\]]+?)\]/g, function (face) { // 转义图片
var src = face.replace(/^file\[/g, '').replace(/\]/g, '');;
return '<a href="'+src+'" target="_blank"/><i style="font-size: 26px;color: #606266" class="el-icon-folder-checked"></i></a>';
})
}
function replaceMutiFile(str){
return str.replace(/mutiFile\[(.*?)\]/g, function (result) {
var mutiFiles=result.match(/mutiFile\[(.*?)\]/)
if (mutiFiles.length<2){
return result;
}
//return result;
var info=JSON.parse(mutiFiles[1])
var imgSrc="";
switch(info.ext){
case ".mp3":
imgSrc="/static/images/ext/MP3.png";
break;
case ".zip":
imgSrc="/static/images/ext/ZIP.png";
break;
case ".txt":
imgSrc="/static/images/ext/TXT.png";
break;
case ".7z":
imgSrc="/static/images/ext/7z.png";
break;
case ".bpm":
imgSrc="/static/images/ext/BMP.png";
break;
case ".png":
imgSrc="/static/images/ext/PNG.png";
break;
case ".jpg":
imgSrc="/static/images/ext/JPG.png";
break;
case ".jpeg":
imgSrc="/static/images/ext/JPEG.png";
break;
case ".pdf":
imgSrc="/static/images/ext/PDF.png";
break;
case ".doc":
imgSrc="/static/images/ext/DOC.png";
break;
case ".docx":
imgSrc="/static/images/ext/DOCX.png";
break;
case ".rar":
imgSrc="/static/images/ext/RAR.png";
break;
case ".xlsx":
imgSrc="/static/images/ext/XLSX.png";
break;
case ".csv":
imgSrc="/static/images/ext/XLSX.png";
break;
default:
imgSrc="/static/images/ext/default.png";
break;
}
var html= `<div onclick="window.open('`+info.path+`')" class="productCard">
<div><img src='`+imgSrc+`' style='width: 38px;height: 38px;' /></div>
<div class="productCardTitle">
<div class="productCardTitle">`+info.name+`</div>
<div style="font-size: 12px;color: #666">`+formatFileSize(info.size)+`</div>
</div>
</div>`;
return html;
// return '<a href="'+src+'" target="_blank"/><i style="font-size: 26px;color: #606266" class="el-icon-folder-checked"></i></a>';
})
}
function formatFileSize(fileSize) {
if (fileSize < 1024) {
return fileSize + 'B';
} else if (fileSize < (1024*1024)) {
var temp = fileSize / 1024;
temp = temp.toFixed(2);
return temp + 'KB';
} else if (fileSize < (1024*1024*1024)) {
var temp = fileSize / (1024*1024);
temp = temp.toFixed(2);
return temp + 'MB';
} else {
var temp = fileSize / (1024*1024*1024);
temp = temp.toFixed(2);
return temp + 'GB';
}
}
function urlEncode (str) {
str = (str + '').toString();
return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28'). replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}
function AsciiToString(i){
return String.fromCharCode(i)
}
function urlDecode(zipStr){
var uzipStr = '';
for (var i = 0; i < zipStr.length; i += 1) {
var chr = zipStr.charAt(i);
if (chr === '+') {
uzipStr += ' ';
} else if (chr === '%') {
var asc = zipStr.substring(i + 1, i + 3);
if (parseInt('0x' + asc) > 0x7f) {
uzipStr += decodeURI('%' + asc.toString() + zipStr.substring(i+3, i+9).toString());
i += 8;
}else{
uzipStr += AsciiToString(parseInt('0x' + asc));
i += 2;
}
}else{
uzipStr += chr;
}
}
return uzipStr;
}
function replaceProduct(str){
return str.replace(/^product\[(.*?)\]$/g, function (product) {
if(!arguments[1]){
return;
}
let jsonStr=arguments[1].replace(/\'/g,'"');
try{
let info=JSON.parse(jsonStr);
if(typeof info=="undefined"){
return;
}
if(!info.title) info.title="智能客服系统产品卡片";
let priceHtml="";
if(info.price){
priceHtml='<div class="productCardPrice">'+info.price+'</div>';
}
if(info.img){
info.img="<img src='"+info.img+"'/>";
}else{
info.img="";
}
let urlHtml=""
if(info.url){
urlHtml='<a href="'+info.url+'" target="_blank">查看</a>';
}
let html= `<div class="productCard">`+info.img+`<div class="productInfo"><h2 class="productCardTitle">`+info.title+`</h2><div class="productCardBtn">`+priceHtml+urlHtml+`</div></div></div>`;
return html;
}catch (e) {
return jsonStr;
}
});
}
function replaceSpecialTag(str,baseUrl) {
if(typeof baseUrl=="undefined"){
baseUrl="";
}
str=str.replace(/\n/g,"<br>");
str=replaceFace(str,baseUrl);
str=replaceImage(str,baseUrl);
str=replaceAudio(str)
str=replaceFile(str)
str=replaceMutiFile(str)
str=replaceProduct(str);
return str;
}
function filter (obj){
var imgType = ["image/jpeg","image/png","image/jpg","image/gif"];
var filetypes = imgType;
var isnext = false;
for (var i = 0; i < filetypes.length; i++) {
if (filetypes[i] == obj.type) {
return true;
}
}
return false;
}
function sleep(time) {
var startTime = new Date().getTime() + parseInt(time, 10);
while(new Date().getTime() < startTime) {}
}
//检测语种
function checkLang() {
// 尝试从查询参数中获取语言设置,如果不存在则尝试从本地存储中获取
let lang = getQuery("lang") || getLocalStorage("lang") || navigator.language;
// 根据浏览器语言设置默认语言
switch (lang) {
// 美式英语、英式英语、澳大利亚英语、加拿大英语和新西兰英语统一使用英语
case "en-US":
case "en-GB":
case "en-AU":
case "en-CA":
case "en-NZ":
case "en":
lang = "en-US";
break;
// 中文简体
case "zh-CN":
case "cn":
lang = "zh-CN";
break;
// 中文繁体,包括台湾和香港
case "zh-TW":
lang = "zh-TW";
break;
case "zh-HK":
lang = "zh-HK";
break;
case "ru-RU":
case "ru":
lang = "ru-RU";
break;
case "kk-KZ":
lang = "kk-KZ";
break;
default:
lang = "en-US";
break;
}
return lang;
}
//动态加载js
function loadJsFile(name,callback) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = '/static/js/' + name;
script.defer = true;
if(typeof(callback)=='function'){
script.onload = script.onreadystatechange = function () {
if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete"){
callback();
script.onload = script.onreadystatechange = null;
}
};
}
document.head.appendChild(script);
}
//修改url参数
function changeURLPar(destiny, par, par_value) {
var pattern = par.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + '=([^&]*)';
var replaceText = par + '=' + par_value;
if (destiny.match(new RegExp(pattern))) {
return destiny.replace(new RegExp(pattern, 'g'), replaceText);
} else {
if (destiny.match('[\?]')) {
return destiny + '&' + replaceText;
} else {
return destiny + '?' + replaceText;
}
}
}
//获取url中的get参数
function getQuery(key) {
// 获取所有参数
var query = window.location.search.substring(1);
var hash = window.location.hash.substring(1);
// 如果锚点后面有参数把锚点后面的参数加入到search参数中
if(hash.indexOf("?") > -1){
query += "&" + hash.split("?")[1];
}
var key_values = query.split("&");
var params = {};
// 遍历参数并存入params对象
key_values.map(function (key_val){
var key_val_arr = key_val.split("=");
params[key_val_arr[0]] = key_val_arr[1];
});
// 如果找到了key对应的参数返回对应值
if(typeof params[key]!="undefined"){
return params[key];
}
// 如果没找到,返回空字符串
return "";
}
function utf8ToB64(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
function urlDecode2(str) {
return decodeURIComponent(str.replace(/\%20/g, '+'));
}
function b64ToUtf8(str) {
str=urlDecode2(str);
return decodeURIComponent(escape(window.atob(str)));
}
//存储localStorge
function setLocalStorage(key,obj){
if(!navigator.cookieEnabled||typeof window.localStorage == 'undefined'){
return false;
}
localStorage.setItem(key, JSON.stringify(obj));
return true;
}
//读取localStorge
function getLocalStorage(key){
if(!navigator.cookieEnabled||typeof window.localStorage == 'undefined'){
return false;
}
var str=localStorage.getItem(key);
if(!str){
return "";
}
return JSON.parse(str);
}
//设置cookie
function setCookie(name,value,expireTime) {
var exp = new Date();
exp.setTime(exp.getTime() + expireTime*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
//读取cookie
function getCookie(name) {
var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
if(arr=document.cookie.match(reg)){
return unescape(arr[2]);
}else{
return null;
}
}
function setFakeCookie(name,value,expire) {
var obj={
"create_time":getNowDate(),
"expire":expire,
"value":value,
}
localStorage.setItem(name, JSON.stringify(obj));
}
function getFakeCookie(name) {
var obj=JSON.parse(localStorage.getItem(name));
if(!obj){
return "";
}
var visitorExpireSecond=new Date(obj.create_time).getTime()+parseInt(obj.expire)*1000;
var nowTime=getTimestamp();
if(visitorExpireSecond<=nowTime){
localStorage.removeItem(name);
return "";
}
return obj.value;
}
var imgs = document.querySelectorAll('img');
//offsetTop是元素与offsetParent的距离循环获取直到页面顶部
function getTop(e) {
var T = e.offsetTop;
while(e = e.offsetParent) {
T += e.offsetTop;
}
return T;
}
function lazyLoad(imgs) {
var H = document.documentElement.clientHeight;//获取可视区域高度
var S = document.documentElement.scrollTop || document.body.scrollTop;
for (var i = 0; i < imgs.length; i++) {
if (H + S > getTop(imgs[i])) {
console.log(imgs[i]);
imgs[i].src = imgs[i].getAttribute('data-src');
}
}
}
function loadImage(url){
var image = new Image();
image.src = url;
console.log(image);
}
function image2Canvas(image) {
var canvas = document.createElement('canvas')
var ctx = canvas.getContext('2d')
canvas.width = image.naturalWidth
canvas.height = image.naturalHeight
ctx.drawImage(image, 0, 0, canvas.width, canvas.height)
return canvas
}
function canvas2DataUrl(canvas, quality, type) {
return canvas.toDataURL(type || 'image/jpeg', quality || 0.8)
}
function dataUrl2Image(dataUrl, callback) {
var image = new Image()
image.onload = function() {
callback(image)
}
image.src = dataUrl
}
function dateFormat(fmt, date) {
let ret;
const opt = {
"Y+": date.getFullYear().toString(), // 年
"m+": (date.getMonth() + 1).toString(), // 月
"d+": date.getDate().toString(), // 日
"H+": date.getHours().toString(), // 时
"M+": date.getMinutes().toString(), // 分
"S+": date.getSeconds().toString() // 秒
// 有其他格式化字符需求可以继续添加,必须转化成字符串
};
for (let k in opt) {
if(k!="Y+"){
var length=opt[k].length;
if(length<2){
opt[k]="0"+opt[k];
}
}
ret = new RegExp("(" + k + ")").exec(fmt);
if (ret) {
fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
};
};
return fmt;
}
/**
* 人性化时间
* @param {Object} timestamp
*/
function beautifyTime(timestamp,lang){
var mistiming = Math.round(new Date() / 1000)-timestamp;
mistiming = Math.abs(mistiming)
if(lang=="en"){
var postfix = mistiming>0 ? 'ago' : 'later'
var arrr = [' years ',' months ',' weeks ',' days ',' hours ',' minutes ',' seconds '];
var just='just now';
}else if(lang=="tw"){
var postfix = mistiming>0 ? '前' : '後'
var arrr = ['年','個月','周','天','小時','分鐘','秒'];
var just='剛剛';
}else{
var postfix = mistiming>0 ? '前' : '后'
var arrr = ['年','个月','周','天','小时','分钟','秒'];
var just='刚刚';
}
if(mistiming<=1){
return just;
}
var arrn = [31536000,2592000,604800,86400,3600,60,1];
for(var i=0; i<7; i++){
var inm = Math.floor(mistiming/arrn[i])
if(inm!=0){
return inm+arrr[i] + postfix
}
}
}
/**
* 判断是否是手机访问
* @returns {boolean}
*/
function isMobile() {
if( /Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
return true;
}
return false;
}
//发送ajax的助手函数
function sendAjax(url,method,params,callback){
$.ajax({
type: method,
url: url,
data:params,
headers: {
"token": localStorage.getItem("token")
},
success: function(data) {
callback(data);
},
error: function(data) {
var res=JSON.parse(data.responseText);
callback(res);
},
});
}
//复制文本
function copyText(text) {
var target = document.createElement('input') //创建input节点
target.value = text // 给input的value赋值
document.body.appendChild(target) // 向页面插入input节点
target.select() // 选中input
document.execCommand("copy"); // 执行浏览器复制命令
document.body.removeChild(target);
return true;
}
function MyHereDoc(){
/*HERE
HERE*/
var here = "HERE";
var reobj = new RegExp("/\\*"+here+"\\n[\\s\\S]*?\\n"+here+"\\*/", "m");
str = reobj.exec(MyHereDoc).toString();
str = str.replace(new RegExp("/\\*"+here+"\\n",'m'),'').toString();
return str.replace(new RegExp("\\n"+here+"\\*/",'m'),'').toString();
}
//js获取当前时间
function getNowDate() {
var myDate = new Date;
var year = myDate.getFullYear(); //获取当前年
var mon = myDate.getMonth() + 1; //获取当前月
if(mon<10){
mon="0"+mon;
}
var date = myDate.getDate(); //获取当前日
if(date<10){
date="0"+date;
}
var hours = myDate.getHours(); //获取当前小时
if(hours<10){
hours="0"+hours;
}
var minutes = myDate.getMinutes(); //获取当前分钟
if(minutes<10){
minutes="0"+minutes;
}
var seconds = myDate.getSeconds(); //获取当前秒
if(seconds<10){
seconds="0"+seconds;
}
var now = year + "-" + mon + "-" + date + " " + hours + ":" + minutes + ":" + seconds;
return now;
}
//获取当前时间戳
function getTimestamp() {
return new Date(getNowDate()).getTime();
}
//删除对象中的空属性
function removePropertyOfNull(obj){
var i = obj.length;
while (i--) {
if (obj[i]===null) {
obj.splice(i, 1);
}
}
return obj;
}
//判断版本号大小
function compareVersion(v1, v2) {
if (v1 == v2) {
return 0;
}
const vs1 = v1.split(".").map(a => parseInt(a));
const vs2 = v2.split(".").map(a => parseInt(a));
const length = Math.min(vs1.length, vs2.length);
for (let i = 0; i < length; i++) {
if (vs1[i] > vs2[i]) {
return 1;
} else if (vs1[i] < vs2[i]) {
return -1;
}
}
if (length == vs1.length) {
return -1;
} else {
return 1;
}
}
function isWeiXin(){
//window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息这个属性可以用来判断浏览器类型
var ua = window.navigator.userAgent.toLowerCase();
//通过正则表达式匹配ua中是否含有MicroMessenger字符串
if(ua.match(/MicroMessenger/i) == 'micromessenger'){
return true;
}else{
return false;
}
}
function isMobile() {
if( /Mobile|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
return true;
}
return false;
}
function replaceHtml(str){
return str.replace(/<\/?.+?\/?>/g,'');
}
function getSelect(){
var selecter = window.getSelection().toString();
if (selecter != null && selecter.trim() != ""){
return selecter.trim();
}
return "";
}
//数组分页
function pagination(pageNo, pageSize, array) {
var offset = (pageNo - 1) * pageSize;
return (offset + pageSize >= array.length) ? array.slice(offset, array.length) : array.slice(offset, offset + pageSize);
}
function mod(n, m) {
return ((n % m) + m) % m;
}
//动态加载css
function dynamicLoadCss(url){
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.type='text/css';
link.rel = 'stylesheet';
link.href = url;
head.appendChild(link);
}
//动态加载js文件
function dynamicLoadJs(url, callback){
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
if(typeof(callback)=='function'){
script.onload = script.onreadystatechange = function () {
if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete"){
callback();
script.onload = script.onreadystatechange = null;
}
};
}
head.appendChild(script);
}
//数组导出CSV文件
function exportCSV(jsonData,fileName){
if(!jsonData || jsonData.length==0){
return;
}
if(!fileName){
fileName="exportCSV.csv";
}
let one=jsonData[0];
let csvText="";
for(let key in one){
csvText+=key+","
}
csvText=trim(csvText,",")+"\n";
//增加\t为了不让表格显示科学计数法或者其他格式
for(let i = 0 ; i < jsonData.length ; i++ ){
let row="";
for(let item in jsonData[i]){
row+=`${jsonData[i][item] + '\t'},`;
}
csvText+=trim(row,",")+'\n';
}
//encodeURIComponent解决中文乱码
let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(csvText);
//通过创建a标签实现
let link = document.createElement("a");
link.href = uri;
//对下载的文件命名
link.download = fileName;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
//js实现类似php trim函数
function trim(str, char) {
if (char) {
str=str.replace(new RegExp('^\\'+char+'+|\\'+char+'+$', 'g'), '');
}
return str.replace(/^\s+|\s+$/g, '');
};
//截取指定个数的字符串
function truncateString(inputString, maxLength) {
let currentLength = 0;
let outputString = '';
let i = 0;
while (i < inputString.length && currentLength < maxLength) {
const char = inputString[i];
const charCode = inputString.charCodeAt(i);
// 如果字符是英文字符ASCII码范围32-126或中文字符
if ((charCode >= 32 && charCode <= 126) || (charCode >= 19968 && charCode <= 40869)) {
outputString += char;
currentLength += 1; // 英文字符算一个字符,中文字符也算一个字符
} else {
// 其他字符,如表情符号等,可能会占用多个字符宽度,视情况增加字符宽度
currentLength += 2; // 增加字符宽度,可以根据需要调整
outputString += char;
}
i++;
}
return outputString;
};
//总分页数
function sumPage(pageSize,arr){
var len=arr.length;
if(len<pageSize){
return 1;
}
var pages=len % pageSize == 0 ? len / pageSize : Math.ceil(len / pageSize);
return pages;
}
//数组分页
/**
* @param {Object} pageSize 每页大小
* @param {Object} arr 数组
*/
function returnAllPageFunc(pageSize, arr) {
let pageNum = 1
let pageObj = {
pageNum: 1,
list: []
}
let pageResult = []
let newArr = JSON.parse(JSON.stringify(arr))
let totalPage = newArr.length ? Math.ceil(arr.length / pageSize) : 0 // 计算总页数
for (let i = 1; i <= totalPage; i++) {
if (totalPage == 1) {
pageNum += 1
pageObj.list = newArr.splice(0, arr.length)
} else if (i <= totalPage) {
pageNum += 1
pageObj.list = newArr.splice(0, pageSize)
} else {
pageObj.list = newArr.splice(0, arr.length % pageSize)
}
pageResult.push(pageObj)
pageObj = {
pageNum: pageNum,
list: []
}
}
console.log(`分页:${JSON.stringify(pageResult)}`)
return pageResult
}
function easyFor(arr,callback){
for(var i=0;i<arr.length;i++){
callback(i,arr[i]);
}
}
//今天零点
function getTordayZero(){
return new Date(new Date().toLocaleDateString())
}
//缩短时间
function shortTime(t){
let time=new Date(t);
let today = new Date();
let todayYear = today.getFullYear();
let todayMonth = today.getMonth()+1;
let todayDate = today.getDate();
let targetYear = time.getFullYear();
let targetMonth = time.getMonth()+1;
let targetDate = time.getDate();
let targetHour = time.getHours();
let targetMinutes = time.getMinutes();
let targetSeconds = time.getSeconds();
// 同一天,只显示小时、分钟、秒
if (todayYear === targetYear && todayMonth === targetMonth && todayDate === targetDate) {
if (targetHour < 10) {
targetHour = "0" + targetHour;
}
if (targetMinutes < 10) {
targetMinutes = "0" + targetMinutes;
}
if (targetSeconds < 10) {
targetSeconds = "0" + targetSeconds;
}
return targetHour + ":" + targetMinutes + ":" + targetSeconds;
}
// 同一年,只显示月日等
if (todayYear === targetYear) {
if (targetMonth < 10) {
targetMonth = "0" + targetMonth;
}
if (targetDate < 10) {
targetDate = "0" + targetDate;
}
if (targetHour < 10) {
targetHour = "0" + targetHour;
}
if (targetMinutes < 10) {
targetMinutes = "0" + targetMinutes;
}
if (targetSeconds < 10) {
targetSeconds = "0" + targetSeconds;
}
return `${targetMonth}-${targetDate} `+targetHour + ":" + targetMinutes + ":" + targetSeconds;
}
return t;
}
//强密码验证
function strongPasswordCheck(s) {
var pattern = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![a-z0-9]+$)[a-zA-Z0-9]{6,20}$/;
//如果符合至少6个至多20个字符组成。至少包含一个小写字母一个大写字母和一个数字。
if (pattern.test(s)) {
return true;
} else {
return false;
}
}
//删除对象数组中指定key value的对象
function removeObjects(objects, key, value) {
return objects.filter(function(object) {
return object[key] !== value;
});
}
//延迟展示
function displayGreetings(greetings,callback) {
if(!greetings||greetings.length==0){
return;
}
let delay=0;
for (let i = 0; i < greetings.length; i++) {
if(!greetings[i].delay_second){
delay+=3;
}else{
delay+=greetings[i].delay_second;
}
greetings[i].delay_second=delay;
}
for (let i = 0; i < greetings.length; i++) {
let greeting = greetings[i];
setTimeout(function() {
// 在这里执行你想展示的操作,例如:
callback(greeting);
}, greeting.delay_second*1000);
}
}
//获取浏览器信息
function getBrowserInfo(ua) {
if(/Googlebot/i.test(ua)){
return {
name: "Googlebot",
version: ""
};
}
if(/MicroMessenger/i.test(ua)){
return {
name: "MicroMessenger",
version: ua.match(/MicroMessenger\/([^\s]+)/)[1]
};
}
if(/Mi|MiuiBrowser/i.test(ua)){
return {
name: "MiuiBrowser",
version: ""
};
}
if(/SM/i.test(ua)){
return {
name: "SamsungBrowser",
version: ""
};
}
if(/pclm|OPM|HeyTapBrowser/i.test(ua)){
return {
name: "OPPO Browser",
version: ""
};
}
if(/Vivo/i.test(ua)){
return {
name: "ViVO",
version: ""
};
}
if(/Quark/i.test(ua)){
return {
name: "Quark Browser",
version: ""
};
}
//手机
if (/iPhone/.test(ua)) {
let matchs=ua.match(/CPU\s+iPhone\s+OS\s+([^\s]+)\s+like/);
let version="";
if(matchs && matchs.length>1){
version=matchs[1];
}
return {
name: "Mobile Safari",
version: version
};
}
//猎豹
if (/LBBROWSER/i.test(ua)) {
return {
name: "Liebao Browser",
version: ""
};
}
//QQ
if (/M?QQBrowser/i.test(ua)) {
return {
name: "QQ Browser",
version: ""
};
}
//uc
if (/UCWEB|UCBrowser/i.test(ua)) {
return {
name: "UC Browser",
version: ""
};
}
//360
if (/360SE/i.test(ua)) {
return {
name: "360 Secure Browser",
version: ""
};
}
//QQ 浏览器
if (/QQBrowser/i.test(ua)) {
return {
name: "QQ Browser",
version: ""
};
}
// Baidu Browser
if (/baidubrowser/i.test(ua)) {
return {
name: "Baidu Browser",
version: ""
};
}
// Sogou Browser
if (/MetaSr|Sogou/i.test(ua)) {
return {
name: "Sogou Browser",
version: ""
};
}
// TT Browser
if (/TaoBrowser/i.test(ua)) {
return {
name: "TT Browser",
version: ""
};
}
// SoHu Browser
if (/LBBROWSER|SOHU/i.test(ua)) {
return {
name: "SoHu Browser",
version: ""
};
}
// The World Browser
if (/TheWorld/i.test(ua)) {
return {
name: "The World Browser",
version: ""
};
}
// 2345 Browser
if (/2345Explorer/i.test(ua)) {
return {
name: "2345 Browser",
version: ""
};
}
// Huawei Browser
if (/HuaweiBrowser/i.test(ua)) {
return {
name: "Huawei Browser",
version: ""
};
}
// Kingsoft Browser
if (/K-OTS/i.test(ua)) {
return {
name: "Kingsoft Browser",
version: ""
};
}
if (/360EE/i.test(ua)) {
return {
name: "360 Extreme Explorer",
version: ""
};
}
// Edge
if (/Edg\/\d+/i.test(ua)) {
return {
name: "Microsoft Edge",
version: ua.match(/Edg\/([^\s]+)/)[1]
};
}
// Chrome
if (/Chrome\/\d+/.test(ua)) {
return {
name: "Google Chrome",
version: ua.match(/Chrome\/([^\s]+)/)[1]
};
}
// Firefox
if (/Firefox\/\d+/.test(ua)) {
return {
name: "Mozilla Firefox",
version: ua.match(/Firefox\/([^\s]+)/)[1]
};
}
// Safari
if (/Safari\/\d+/.test(ua)) {
return {
name: "Apple Safari",
version: ua.match(/Safari\/([^\s]+)/)[1]
};
}
if (/MSIE \d+/.test(ua)) {
return {
name: "Microsoft Internet Explorer",
version: ua.match(/MSIE ([^\s]+)/)[1]
};
}
// Other
return {
name: "Other",
version: "Unknown"
};
}
//获取操作系统和设备信息
function getOSAndDeviceInfo(ua) {
const result = {
os:"",
device:""
};
// 操作系统
if (/Android/.test(ua)) {
result.os = "Android";
} else if (/iPhone/i.test(ua)) {
result.os = "iOS";
result.device = "iPhone";
} else if (/Mac/i.test(ua)) {
result.os = "Mac OS X";
result.device = "Mac";
} else if (/Windows/.test(ua)) {
if (/NT 10.0/.test(ua)) {
result.os = "Windows 10";
} else if (/NT 6.2/.test(ua)) {
result.os = "Windows 8";
} else if (/NT 6.1/.test(ua)) {
result.os = "Windows 7";
} else if (/NT 6.0/.test(ua)) {
result.os = "Windows Vista";
} else if (/NT 5.2/.test(ua)) {
result.os = "Windows Server 2003";
} else if (/NT 5.1/.test(ua)) {
result.os = "Windows XP";
}
}else {
result.os = "Other";
}
// 手机品牌型号
if (/Samsung|SM/i.test(ua)) {
result.device = "Samsung";
} else if (/Huawei/i.test(ua)) {
result.device = "Huawei";
} else if (/Xiaomi|M2011K2C/i.test(ua)) {
result.device = "Xiaomi";
} else if (/221013|Redmi/i.test(ua)) {
result.device = "Redmi";
}else if (/OPPO|pclm|OPM|HeyTapBrowser/i.test(ua)) {
result.device = "OPPO";
} else if (/Vivo/i.test(ua)) {
result.device = "Vivo";
} else if (/OnePlus|ne2210/i.test(ua)) {
result.device = "OnePlus ";
}else if (/Sony/i.test(ua)) {
result.device = "Sony";
} else if (/LG/i.test(ua)) {
result.device = "LG";
} else if (/HTC/i.test(ua)) {
result.device = "HTC" ;
} else if (/Nokia/i.test(ua)) {
result.device = "Nokia";
} else if (/Lenovo/i.test(ua)) {
result.device = "Lenovo";
}else if (/ZTE/i.test(ua)) {
result.device = "ZTE";
} else if (/Gionee/i.test(ua)) {
result.device = "Gionee";
} else if (/Meizu/i.test(ua)) {
result.device = "Meizu";
} else if (/Coolpad/i.test(ua)) {
result.device = "Coolpad";
} else if (/Oppo/i.test(ua)) {
result.device = "Oppo";
} else if (/TCL/i.test(ua)) {
result.device = "TCL";
} else if (/RMX/i.test(ua)) {
result.device = "Realme";
}
return result;
}
//使元素可拖动
function makeElementDraggableOnDesktop(elementId) {
const draggableDiv = document.getElementById(elementId);
let isDragging = false;
let dragStartX, dragStartY, offsetX, offsetY;
const container = draggableDiv.parentElement;
draggableDiv.addEventListener('mousedown', function(e) {
isDragging = true;
dragStartX = e.clientX;
dragStartY = e.clientY;
const rect = draggableDiv.getBoundingClientRect();
offsetX = dragStartX - rect.left;
offsetY = dragStartY - rect.top;
});
draggableDiv.addEventListener('mousemove', function(e) {
if (isDragging) {
const x = e.clientX - offsetX;
const y = e.clientY - offsetY;
const maxX = container.clientWidth - draggableDiv.offsetWidth;
const maxY = container.clientHeight - draggableDiv.offsetHeight;
const boundedX = Math.max(0, Math.min(x, maxX));
const boundedY = Math.max(0, Math.min(y, maxY));
draggableDiv.style.left = boundedX + 'px';
draggableDiv.style.top = boundedY + 'px';
}
});
draggableDiv.addEventListener('mouseup', function(e) {
isDragging = false;
});
}
// 手机设备可拖动
function makeElementDraggableOnMobile(elementId) {
const draggableDiv = document.getElementById(elementId);
let isDragging = false;
let dragStartX, dragStartY, touchStartX, touchStartY, offsetX, offsetY;
function startDragging(e) {
e.preventDefault();
const touch = e.touches[0];
touchStartX = touch.clientX;
touchStartY = touch.clientY;
const rect = draggableDiv.getBoundingClientRect();
offsetX = touch.clientX - rect.left;
offsetY = touch.clientY - rect.top;
isDragging = true;
}
function moveElement(e) {
e.preventDefault();
if (isDragging) {
const touch = e.touches[0];
let x = touch.clientX - offsetX;
let y = touch.clientY - offsetY;
const maxX = window.innerWidth - draggableDiv.offsetWidth;
const maxY = window.innerHeight - draggableDiv.offsetHeight;
x = Math.min(Math.max(0, x), maxX);
y = Math.min(Math.max(0, y), maxY);
draggableDiv.style.left = x + 'px';
draggableDiv.style.top = y + 'px';
}
}
function stopDragging() {
isDragging = false;
}
draggableDiv.addEventListener('touchstart', startDragging, { passive: false });
draggableDiv.addEventListener('touchmove', moveElement, { passive: false });
draggableDiv.addEventListener('touchend', stopDragging);
}
// 根据设备类型调用不同的可拖动函数
function makeElementDraggable(elementId) {
if (isMobile()) {
makeElementDraggableOnMobile(elementId);
} else {
makeElementDraggableOnDesktop(elementId);
}
}
//获取屏幕媒体流
function getScreenStream(callback) {
if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) {
// 桌面浏览器,使用 getDisplayMedia() 获取屏幕视频流
navigator.mediaDevices.getDisplayMedia({ video: true })
.then((stream) => {
callback(stream);
})
.catch((error) => {
console.error('Error: ' + error);
});
} else if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
// 移动设备或不支持 getDisplayMedia() 的桌面浏览器,使用 getUserMedia() 获取屏幕视频流
navigator.mediaDevices.getUserMedia({ video: { mediaSource: 'screen' } })
.then((stream) => {
callback(stream);
})
.catch((error) => {
console.error('Error: ' + error);
});
} else {
console.error('Error: getUserMedia not supported on this browser.');
}
}
//根据多个分隔字符,分隔字符串为数组
function splitString(inputString, separator) {
// 创建正则表达式,匹配传递的多个分隔符
const regEx = new RegExp(`[${separator}]`, 'g');
// 使用 split() 方法将字符串分割成数组
const result = inputString.split(regEx);
// 返回分割后的数组
return result;
}
//循环数组,并且修改数组中的元素
function foreachArray(arr, callback) {
// 遍历数组,执行回调函数修改元素
for (var i = 0; i < arr.length; i++) {
arr[i] = callback(arr[i]);
}
// 返回修改后的数组
return arr;
}
function myBrowser(userAgent) {
var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器
var isQQ = userAgent.indexOf("QQBrowser") > -1; //判断是否QQBrowser浏览器
var isIE = userAgent.indexOf("compatible") > -1
&& userAgent.indexOf("MSIE") > -1; //判断是否IE7~IE10浏览器
var isIE11 = userAgent.indexOf("compatible") === -1
&& userAgent.indexOf("Trident") > -1; //判断是否IE11浏览器
var isEdge = userAgent.indexOf("Edg") > -1; //判断是否IE的Edge浏览器
var isFF = userAgent.indexOf("Firefox") > -1; //判断是否Firefox浏览器
var isSafari = userAgent.indexOf("Safari") > -1
&& userAgent.indexOf("Mac") > -1; //判断是否Safari浏览器
var isChrome = userAgent.indexOf("Chrome") > -1
&& userAgent.indexOf("; Win") > -1
&& userAgent.indexOf("Safari") > -1; //判断Chrome浏览器
var is360 = userAgent.indexOf("Chrome") > -1
&& userAgent.indexOf("; WOW") > -1
&& userAgent.indexOf("Safari") > -1; //判断360浏览器
var isMobile=userAgent.indexOf("Mobile") > -1;
var isWechat=/MicroMessenger/i.test(userAgent);
var isMi=userAgent.indexOf("Mobile") > -1 && /Mi|MiuiBrowser/i.test(userAgent);
var isHuawei=userAgent.indexOf("Mobile") > -1 && /huawei/i.test(userAgent);
var isSamsung=userAgent.indexOf("Mobile") > -1 && /SM/i.test(userAgent);
var isOPPO =userAgent.indexOf("Mobile") > -1 && /pclm|OPM|HeyTapBrowser/i.test(userAgent);
var isVivo=userAgent.indexOf("Mobile") > -1 && /Vivo/i.test(userAgent);
var isBaidu=userAgent.indexOf("Mobile") > -1 && /Baidu/i.test(userAgent);
var isUC = /UcBrowser/i.test(userAgent); //判断是否UC浏览器
if (isIE) {
var reIE = /MSIE (\d+)\.\d+;/;
// match() 返回一个数组。数组第一项是匹配到的所有文本;数组第二项是正则中小括号匹配到的文本
var matchReg = userAgent.match(reIE)
var fIEVersion = matchReg[1];
if (fIEVersion == 7) {
return "IE7及其以下";
} else if (fIEVersion == 8) {
return "IE8";
} else if (fIEVersion == 9) {
return "IE9";
} else if (fIEVersion == 10) {
return "IE10";
} else {
return "0";
}//IE版本过低
return "IE";
}
if (isWechat) return "Wechat";
if (is360) return "360";
if(isMi) return "XiaoMi";
if(isHuawei) return "Huawei";
if (isUC) return "UcBrowser";
if (isQQ) return "QQBrowser";
if (isIE11) return "IE11";
if (isSamsung) return "SamsungBrowser";
if (isOPPO) return "OPPO";
if (isVivo) return "Vivo";
if (isBaidu) return "Baidu";
if (isEdge) {
return "Edge";
}
if (isFF) {
return "Firefox";
}
if (isSafari) {
return "Safari";
}
if (isChrome) {
return "Chrome";
}
if (isOpera) {
return "Opera";
}
if(isMobile){
return "Mobile";
}
}
function makeResizable(className,callback) {
var isResizing = false;
var lastY = 0;
$(document).on('mouseover', '.' + className, function(e) {
var $resizableDiv = $('.' + className);
var topOffset = $resizableDiv.offset().top;
var mouseY = e.clientY;
if (mouseY >= topOffset && mouseY <= topOffset + 80) { // 只在鼠标位于上边框20像素范围内时允许拖动
$resizableDiv.addClass('resizing');
}else{
$resizableDiv.removeClass('resizing');
}
});
$(document).on('mousedown', '.' + className, function(e) {
var $resizableDiv = $('.' + className);
var topOffset = $resizableDiv.offset().top;
var mouseY = e.clientY;
if (mouseY >= topOffset && mouseY <= topOffset + 80) { // 只在鼠标位于上边框20像素范围内时允许拖动
isResizing = true;
lastY = e.clientY;
$('body').addClass('resizing');
}
});
$(document).on('mousemove', function(e) {
if (!isResizing) return;
var deltaY = lastY - e.clientY; // 计算鼠标移动的垂直距离
var $resizableDiv = $('.' + className);
var newHeight = $resizableDiv.height() + deltaY;
if(newHeight<150){
newHeight=150;
}
$resizableDiv.height(newHeight);
lastY = e.clientY;
callback();
});
$(document).on('mouseup', function() {
isResizing = false;
$('body').removeClass('resizing');
});
$(document).on('mouseleave', '.' + className, function(e) {
isResizing = false;
$('.' + className).removeClass('resizing');
});
}
function getOsImg(osName) {
let imgUrl="";
if(osName=="Windows"){
imgUrl="<span><img style='width: 13px;margin-right: 5px' src='/static/images/ua/windows11.svg' </span>";
}else if(osName=="Linux"){
imgUrl="<span><img style='width: 13px;margin-right: 5px' src='/static/images/ua/linux.svg' </span>";
}else if(osName=="Mac OS"){
imgUrl="<span><img style='width: 13px;margin-right: 5px' src='/static/images/ua/mac.svg' </span>";
}else if(osName=="iOS"){
imgUrl="<span><img style='width: 15px;margin-right: 5px' src='/static/images/ua/iphone.svg' </span>";
}else if(osName=="Android"||osName=="android"){
imgUrl="<span><img style='width: 14px;margin-right: 5px' src='/static/images/ua/android.svg' </span>";
}
return imgUrl+osName;
}
function getBrowerImg(name) {
let imgUrl="";
if(name=="Safari"){
imgUrl="<span><img style='width: 14px;margin-right: 5px' src='/static/images/ua/safari.svg' </span>";
}else if(name=="Firefox"){
imgUrl="<span><img style='width: 13px;margin-right: 5px' src='/static/images/ua/firefox.svg' </span>";
}else if(name=="Chrome") {
imgUrl = "<span><img style='width: 13px;margin-right: 5px' src='/static/images/ua/chrome.svg' </span>";
}else if(name=="Edge"){
imgUrl="<span><img style='width: 13px;margin-right: 5px' src='/static/images/ua/edge.svg' </span>";
}else{
imgUrl="<span><img style='width: 14px;margin-right: 5px' src='/static/images/ua/defaultbrowser.svg' </span>";
}
return imgUrl+name;
}
//55Sy5pa5OuS4iua1t+iEieiBlOenkeaKgOaciemZkOWFrOWPuArnurPnqI7nmbvorrDlj7c6OTEzMTAxMTRNQTFHV0UzVzdFCuiBlOezu+WcsOWdgDrkuIrmtbfluILlmInlrprljLrph5HmspnmsZ/ot68zMTMx5Y+3MuW5okoK55S16K+d5Y+356CBOjAyMS02MjQxNTI1Ng==
;