// 常用 Strat
/*
* 树型
* list 要遍历的数组
* rootVal 要比较的子ID
* PID 父级ID 属性名
* ID 子级ID 属性名
*/
function tranList(list, rootVal, PID, ID) {
var childItem = [];
for (var i = 0; i < list.length; i++) {
var childObj = {}
if (list[i][PID] == rootVal) {
childObj = list[i];
childObj.children = tranList(list, list[i][ID], PID, ID);
childItem.push(childObj);
}
}
return childItem;
}
// 存取删 Cookie
var Cookie = {
set: function (name, value, days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + (value || "") + expires + "; path=/";
},
get: function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
deleteCookie: function (name) {
document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
},
}
// 获取数据类型
function getType(value) {
const match = Object.prototype.toString.call(value).match(/ (\w+)]/)
return match[1].toLocaleLowerCase()
}
// 深拷贝
function deepClone(obj) {
if (typeof obj != 'object' || typeof obj == null) {
return obj
}
let result;
if (obj instanceof Array) {
result = []
} else {
result = {}
}
// for in 循环拿到的是键(数组是下标) for of拿到的是值
for (let key in obj) {
// hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性
// 不拷贝原型上的属性
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key])
}
}
return result
}
// 判断是否为url地址
function isURL(s) {
return /^http[s]?:\/\/.*/.test(s)
}
// 获得视口的尺寸
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
// ie8及其以下
if (document.compatMode === "BackCompat") {
// 怪异模式
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
} else {
// 标准模式
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
}
}
}
// 防抖
function debounce(handle, delay) {
var timer = null;
return function () {
var _self = this,
_args = arguments;
clearTimeout(timer);
timer = setTimeout(function () {
handle.apply(_self, _args)
}, delay)
}
}
// 节流
function throttle(handler, wait) {
var lastTime = 0;
return function (e) {
var nowTime = new Date().getTime();
if (nowTime - lastTime > wait) {
handler.apply(this, arguments);
lastTime = nowTime;
}
}
}
// 大数相加
function sumBigNumber(a, b) {
var res = '', //结果
temp = 0; //按位加的结果及进位
a = a.split('');
b = b.split('');
while (a.length || b.length || temp) {
//~~按位非 1.类型转换,转换成数字 2.~~undefined==0
temp += ~~a.pop() + ~~b.pop();
res = (temp % 10) + res;
temp = temp > 9;
}
return res.replace(/^0+/, '');
}
// 定义函数 判断一个数组是否包含了另一个数组的全部元素
function isContained(a, b) {
// a和b其中一个不是数组,直接返回false
if (!(a instanceof Array) || !(b instanceof Array)) return false;
const len = b.length;
// a的长度小于b的长度,直接返回false
if (a.length < len) return false;
for (let i = 0; i < len; i++) {
// 遍历b中的元素,遇到a没有包含某个元素的,直接返回false
if (!a.includes(b[i])) return false;
}
// 遍历结束,返回true
return true;
};
// js根据手机屏幕宽度调整zoom
function resize() {
const max = Math.max(window.innerHeight, window.innerWidth);
// document.body.style.zoom = max / 1366;
return max / 1366
};
// 全屏显示元素 -- 场景 -- 需要全屏播放视频,并在浏览器中全屏打开页面
function goToFullScreen(element) {
element = element || document.body;
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen();
}
};
// 退出浏览器全屏状态
function goExitFullscreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
};
// 停止冒泡事件
function stopPropagation(event) {
event = event || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
};
// 确定设备类型
function isMobile() {
return !!navigator.userAgent.match(
/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
);
};
// 判断设备是安卓还是IOS
function isAndroid() {
return /android/i.test(navigator.userAgent.toLowerCase());
};
function isIOS() {
let reg = /iPhone|iPad|iPod|iOS|Macintosh/i;
return reg.test(navigator.userAgent.toLowerCase());
};
// 获取浏览器类型及其版本
function getExplorerInfo() {
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("msie")
? {
//ie < 11
type: "IE",
version: Number(t.match(/msie ([\d]+)/)[1]),
}
: !!t.match(/trident\/.+?rv:(([\d.]+))/)
? {
// ie 11
type: "IE",
version: 11,
}
: 0 <= t.indexOf("edge")
? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("firefox")
? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("chrome")
? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("opera")
? {
type: "Opera",
version: Number(t.match(/opera.([\d]+)/)[1]),
}
: 0 <= t.indexOf("Safari")
? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1]),
}
: {
type: t,
version: -1,
};
};
// 生成随机字符串
function randomString(len) {
let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
let strLen = chars.length;
let randomStr = "";
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;
};
// 字符串首字母大写
function fistLetterUpper(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
};
// 生成指定范围内的随机数
function randomNum(min, max) {
Math.floor(Math.random() * (max - min + 1)) + min
}
// 打乱数组的顺序
function shuffleArray(array) {
return array.sort(() => 0.5 - Math.random())
}
// 格式化货币1
function formatMoney(money) {
return money.replace(new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',')
}
// 格式化货币2
function formatMoneyNum(money) {
return money.toLocaleString()
}
/* 数组去重 */
function unique1(arr) {
return [...new Set(arr)]
}
function unique2(arr) {
var obj = {};
return arr.filter(ele => {
if (!obj[ele]) {
obj[ele] = true;
return true;
}
})
}
function unique3(arr) {
var result = [];
arr.forEach(ele => {
if (result.indexOf(ele) == -1) {
result.push(ele)
}
})
return result;
}
// 返回当前的时间(年月日时分秒)
function getDateTime() {
var date = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 1,
day = date.getDate(),
hour = date.getHours() + 1,
minute = date.getMinutes(),
second = date.getSeconds();
month = checkTime(month);
day = checkTime(day);
hour = checkTime(hour);
minute = checkTime(minute);
second = checkTime(second);
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
}
// 取消冒泡的兼容代码
function stopBubble(e) {
if (e && e.stopPropagation) {
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}
}
/* 检验字符串是否是回文 */
function isPalina(str) {
if (Object.prototype.toString.call(str) !== '[object String]') {
return false;
}
var len = str.length;
for (var i = 0; i < len / 2; i++) {
if (str[i] != str[len - 1 - i]) {
return false;
}
}
return true;
}
function isPalindrome(str) {
str = str.replace(/\W/g, '').toLowerCase();
console.log(str)
return (str == str.split('').reverse().join(''))
}
/* 获取url中的参数 */
function getWindonHref() {
var sHref = window.location.href;
var args = sHref.split('?');
if (args[0] === sHref) {
return '';
}
var hrefarr = args[1].split('#')[0].split('&');
var obj = {};
for (var i = 0; i < hrefarr.length; i++) {
hrefarr[i] = hrefarr[i].split('=');
obj[hrefarr[i][0]] = hrefarr[i][1];
}
return obj;
}
function getUrlParam(sUrl, sKey) {
var result = {};
sUrl.replace(/(\w+)=(\w+)(?=[&|#])/g, function (ele, key, val) {
if (!result[key]) {
result[key] = val;
} else {
var temp = result[key];
result[key] = [].concat(temp, val);
}
})
if (!sKey) {
return result;
} else {
return result[sKey] || '';
}
}
function getUrlParam(name) { // 获取url参数
let reg = new RegExp('(^|&?)' + name + '=([^&]*)(&|$)', 'i')
let r = window.location.href.substr(1).match(reg)
if (r != null) {
return decodeURI(r[2])
}
return undefined
}
/* 数组排序 */
// 快排 [left] + min + [right]
function quickArr(arr) {
if (arr.length <= 1) {
return arr;
}
var left = [],
right = [];
var pIndex = Math.floor(arr.length / 2);
var p = arr.splice(pIndex, 1)[0];
for (var i = 0; i < arr.length; i++) {
if (arr[i] <= p) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
// 递归
return quickArr(left).concat([p], quickArr(right));
}
// 冒泡
function bubbleSort(arr) {
for (var i = 0; i < arr.length - 1; i++) {
for (var j = i + 1; j < arr.length; j++) {
if (arr[i] > arr[j]) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
function bubbleSort(arr) {
var len = arr.length;
for (var i = 0; i < len - 1; i++) {
for (var j = 0; j < len - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
var temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
// 遍历Dom树
// 给定页面上的DOM元素,将访问元素本身及其所有后代(不仅仅是它的直接子元素)
// 对于每个访问的元素,函数讲元素传递给提供的回调函数
function traverse(element, callback) {
callback(element);
var list = element.children;
for (var i = 0; i < list.length; i++) {
traverse(list[i], callback);
}
}
// 原生js封装ajax
function ajax(method, url, callback, data, flag) {
var xhr;
flag = flag || true;
method = method.toUpperCase();
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHttp');
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(2)
callback(xhr.responseText);
}
}
if (method == 'GET') {
var date = new Date(),
timer = date.getTime();
xhr.open('GET', url + '?' + data + '&timer' + timer, flag);
xhr.send()
} else if (method == 'POST') {
xhr.open('POST', url, flag);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(data);
}
}
// 异步加载script
function loadScript(url, callback) {
var oscript = document.createElement('script');
if (oscript.readyState) { // ie8及以下版本
oscript.onreadystatechange = function () {
if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') {
callback();
}
}
} else {
oscript.onload = function () {
callback()
};
}
oscript.src = url;
document.body.appendChild(oscript);
}
// jsonp底层方法
function jsonp(url, callback) {
var oscript = document.createElement('script');
if (oscript.readyState) { // ie8及以下版本
oscript.onreadystatechange = function () {
if (oscript.readyState === 'complete' || oscript.readyState === 'loaded') {
callback();
}
}
} else {
oscript.onload = function () {
callback()
};
}
oscript.src = url;
document.body.appendChild(oscript);
}
// 函数柯里化
//是把接受多个参数的函数变换成接受一个单一参数(最初函数的第一个参数)的函数,并且返回接受余下的参数且返回结果的新函数的技术
function curryIt(fn) {
var length = fn.length,
args = [];
var result = function (arg) {
args.push(arg);
length--;
if (length <= 0) {
return fn.apply(this, args);
} else {
return result;
}
}
return result;
}
// 加载js || css || style
function loadRes(name, type, fn) { // 加载js || css || style
let ref
if (type === 'js') { // 外部js
ref = document.createElement('script')
ref.setAttribute('type', 'text/JavaScript')
ref.setAttribute('src', name)
} else if (type === 'css') { // 外部css
ref = document.createElement('link')
ref.setAttribute('rel', 'stylesheet')
ref.setAttribute('type', 'text/css')
ref.setAttribute('href', name)
} else if (type === 'style') { // style
ref = document.createElement('style')
ref.innerhtml = name
}
if (typeof ref !== 'undefined') {
document.getElementsByTagName('head')[0].appendChild(ref)
ref.onload = function () { // 加载完成执行
typeof fn === 'function' && fn()
}
}
}
// 本地存储
const store = {
set: function (name, value, day) { // 设置
let d = new Date()
let time = 0
day = (typeof (day) === 'undefined' || !day) ? 1 : day // 时间,默认存储1天
time = d.setHours(d.getHours() + (24 * day)) // 毫秒
localStorage.setItem(name, JSON.stringify({
data: value,
time: time
}))
},
get: function (name) { // 获取
let data = localStorage.getItem(name)
if (!data) {
return null
}
let obj = JSON.parse(data)
if (new Date().getTime() > obj.time) { // 过期
localStorage.removeItem(name)
return null
} else {
return obj.data
}
},
clear: function (name) { // 清空
if (name) { // 删除键为name的缓存
localStorage.removeItem(name)
} else { // 清空全部
localStorage.clear()
}
}
}
// fetch请求的封装
const fetch = function (url, setting) {
let opts = { // 设置参数的初始值
method: (setting.method || 'GET').toUpperCase(), // 请求方式
headers: setting.headers || {}, // 请求头设置
credentials: setting.credentials || true, // 设置cookie是否一起发送
body: setting.body || {},
mode: setting.mode || 'no-cors', // 可以设置 cors, no-cors, same-origin
redirect: setting.redirect || 'follow', // follow, error, manual
cache: setting.cache || 'default' // 设置 cache 模式 (default, reload, no-cache)
}
let dataType = setting.dataType || 'json' // 解析方式
let data = setting.data || '' // 参数
let paramsFormat = function (obj) { // 参数格式
var str = ''
for (var i in obj) {
str += `${i}=${obj[i]}&`
}
return str.split('').slice(0, -1).join('')
}
if (opts.method === 'GET') {
url = url + (data ? `?${paramsFormat(data)}` : '')
} else {
setting.body = data || {}
}
return new Promise((resolve, reject) => {
fetch(url, opts).then(async res => {
let data = dataType === 'text' ? await res.text() : dataType === 'blob' ? await res.blob() : await res.json()
resolve(data)
}).catch(e => {
reject(e)
})
})
}
// 判断是否为微信
const isWx = function () {
var ua = window.navigator.userAgent.toLowerCase()
if (String(ua.match(/MicroMessenger/i)) === 'micromessenger') {
return true
}
return false
}
// 复制功能
const copyTxt = function (text, fn) {
if (typeof document.execCommand !== 'function') {
console.log('复制失败,请长按复制')
return
}
var dom = document.createElement('textarea')
dom.value = text
dom.setAttribute('style', 'display: block;width: 1px;height: 1px;')
document.body.appendChild(dom)
dom.select()
var result = document.execCommand('copy')
document.body.removeChild(dom)
if (result) {
console.log('复制成功')
typeof fn === 'function' && fn()
return
}
if (typeof document.createRange !== 'function') {
console.log('复制失败,请长按复制')
return
}
var range = document.createRange()
var div = document.createElement('div')
div.innerhtml = text
div.setAttribute('style', 'height: 1px;fontSize: 1px;overflow: hidden;')
document.body.appendChild(div)
range.selectNode(div)
var selection = window.getSelection()
console.log(selection)
if (selection.rangeCount > 0) {
selection.removeAllRanges()
}
selection.addRange(range)
document.execCommand('copy')
typeof fn === 'function' && fn()
console.log('复制成功')
}
//判断两个数组是否相等
const arrayEqual = function (arr1, arr2) {
if (arr1 === arr2) return true;
if (arr1.length != arr2.length) return false;
for (let i = 0; i < arr1.length; ++i) {
if (arr1[i] !== arr2[i]) return false;
}
return true;
}
// 过滤html代码
const filterTag = function (str) { // 过滤html代码(把<>转换)
str = str.replace(/&/ig, '&')
str = str.replace(/</ig, '<')
str = str.replace(/>/ig, '>')
str = str.replace(' ', ' ')
return str
}
// 将阿拉伯数字翻译成中文的大写数字
const numberToChinese = function (num) {
let AA = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十')
let BB = new Array('', '十', '百', '仟', '萬', '億', '点', '')
let a = ('' + num).replace(/(^0*)/g, '').split('.')
let k = 0
let re = ''
for (let i = a[0].length - 1; i >= 0; i--) {
switch (k) {
case 0:
re = BB[7] + re
break
case 4:
if (!new RegExp('0{4}//d{' + (a[0].length - i - 1) + '}$').test(a[0])) {
re = BB[4] + re
}
break
case 8:
re = BB[5] + re
BB[7] = BB[5]
k = 0
break
}
if (k % 4 === 2 && a[0].charAt(i + 2) !== 0 && a[0].charAt(i + 1) === 0) {
re = AA[0] + re
}
if (a[0].charAt(i) !== 0) {
re = AA[a[0].charAt(i)] + BB[k % 4] + re
}
k++
}
if (a.length > 1) { // 加上小数部分(如果有小数部分)
re += BB[6]
for (let i = 0; i < a[1].length; i++) {
re += AA[a[1].charAt(i)]
}
}
if (re === '一十') {
re = '十'
}
if (re.match(/^一/) && re.length === 3) {
re = re.replace('一', '')
}
return re
}
// 原生dom操作
const dom = {
$: function (selector) {
let type = selector.substring(0, 1)
if (type === '#') {
if (document.querySelecotor) return document.querySelector(selector)
return document.getElementById(selector.substring(1))
} else if (type === '.') {
if (document.querySelecotorAll) return document.querySelectorAll(selector)
return document.getElementsByClassName(selector.substring(1))
} else {
return document['querySelectorAll' ? 'querySelectorAll' : 'getElementsByTagName'](selector)
}
},
hasClass: function (ele, name) { /* 检测类名 */
return ele.className.match(new RegExp('(\\s|^)' + name + '(\\s|$)'))
},
addClass: function (ele, name) { /* 添加类名 */
if (!this.hasClass(ele, name)) ele.className += ' ' + name
},
removeClass: function (ele, name) { /* 删除类名 */
if (this.hasClass(ele, name)) {
let reg = new RegExp('(\\s|^)' + name + '(\\s|$)')
ele.className = ele.className.replace(reg, '')
}
},
replaceClass: function (ele, newName, oldName) { /* 替换类名 */
this.removeClass(ele, oldName)
this.addClass(ele, newName)
},
siblings: function (ele) { /* 获取兄弟节点 */
console.log(ele.parentNode)
let chid = ele.parentNode.children,
eleMatch = []
for (let i = 0, len = chid.length; i < len; i++) {
if (chid[i] !== ele) {
eleMatch.push(chid[i])
}
}
return eleMatch
},
getByStyle: function (obj, name) { /* 获取行间样式属性 */
if (obj.currentStyle) {
return obj.currentStyle[name]
} else {
return getComputedStyle(obj, false)[name]
}
},
domToStirng: function (htmlDOM) { /* DOM转字符串 */
var div = document.createElement('div')
div.appendChild(htmlDOM)
return div.innerHTML
},
stringToDom: function (htmlString) { /* 字符串转DOM */
var div = document.createElement('div')
div.innerHTML = htmlString
return div.children[0]
}
}
// 图片地址转base64
const getBase64 = function (img) { //传入图片路径,返回base64,使用getBase64(url).then(function(base64){},function(err){});
let getBase64Image = function (img, width, height) { //width、height调用时传入具体像素值,控制大小,不传则默认图像大小
let canvas = document.createElement("canvas");
canvas.width = width ? width : img.width;
canvas.height = height ? height : img.height;
let ctx = canvas.getContext("2d");
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
let dataURL = canvas.toDataURL();
return dataURL;
}
let image = new Image();
image.crossOrigin = '';
image.src = img;
let deferred = $.Deferred();
if (img) {
image.onload = function () {
deferred.resolve(getBase64Image(image));
}
return deferred.promise();
}
}
// base64图片下载功能
const downloadFile = function (base64, fileName) { //base64图片下载功能
let base64ToBlob = function (code) {
let parts = code.split(';base64,');
let contentType = parts[0].split(':')[1];
let raw = window.atob(parts[1]);
let rawLength = raw.length;
let uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], {
type: contentType
});
};
let aLink = document.createElement('a');
let blob = base64ToBlob(base64); //new Blob([content]);
let evt = document.createEvent("HTMLEvents");
evt.initEvent("click", true, true); //initEvent不加后两个参数在FF下会报错 事件类型,是否冒泡,是否阻止浏览器的默认行为
aLink.download = fileName;
aLink.href = URL.createObjectURL(blob);
aLink.click();
}
常用 js
于 2023-09-26 13:37:27 首次发布