/**
* @param { * } file 图片文件
*/
export const fileToBase64 = file => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function (e) {
return e.target.result
};
};
复制代码
export function getTreeData(data, pid, pidName = 'parentId', idName = 'id', childrenName = 'children', key) {
let arr = [];
for (let i = 0; i < data.length; i++) {
if (data[i][pidName] == pid) {
data[i].key = data[i][idName];
data[i][childrenName] = getTreeData(data, data[i][idName], pidName, idName, childrenName);
arr.push(data[i]);
}
}
return arr;
}
复制代码
export function foreachTree(data, childrenName = 'children', callback) {
for (let i = 0; i < data.length; i++) {
callback(data[i]);
if (data[i][childrenName] && data[i][childrenName].length > 0) {
foreachTree(data[i][childrenName], childrenName, callback);
}
}
}
复制代码
export function traceParentNode(pid, data, rootPid, pidName = 'parentId', idName = 'id', childrenName = 'children') {
let arr = [];
foreachTree(data, childrenName, (node) => {
if (node[idName] == pid) {
arr.push(node);
if (node[pidName] != rootPid) {
arr = arr.concat(traceParentNode(node[pidName], data, rootPid, pidName, idName));
}
}
});
return arr;
}
复制代码
export function traceChildNode(id, data, pidName = 'parentId', idName = 'id', childrenName = 'children') {
let arr = [];
foreachTree(data, childrenName, (node) => {
if (node[pidName] == id) {
arr.push(node);
arr = arr.concat(traceChildNode(node[idName], data, pidName, idName, childrenName));
}
});
return arr;
}
复制代码
/**
* @param { object } items 后台获取的数据
* @param { * } id 数据中的id
* @param { * } link 生成树形结构的依据
*/
export const createTree = (items, id = null, link = 'pid') =>{
items.filter(item => item[link] === id).map(item => ({ ...item, children: createTree(items, item.id) }));
};
复制代码
/**
* @param {*} item
* @param { array } data
*/
export function inArray(item, data) {
for (let i = 0; i < data.length; i++) {
if (item === data[i]) {
return i;
}
}
return -1;
}
复制代码
/**
* @param { string } osVersion
*/
export function OutOsName(osVersion) {
if(!osVersion){
return
}
let str = osVersion.substr(0, 3);
if (str === "5.0") {
return "Win 2000"
} else if (str === "5.1") {
return "Win XP"
} else if (str === "5.2") {
return "Win XP64"
} else if (str === "6.0") {
return "Win Vista"
} else if (str === "6.1") {
return "Win 7"
} else if (str === "6.2") {
return "Win 8"
} else if (str === "6.3") {
return "Win 8.1"
} else if (str === "10.") {
return "Win 10"
} else {
return "Win"
}
}
复制代码
/**
* 0: ios
* 1: android
* 2: 其它
*/
export function getOSType() {
let u = navigator.userAgent, app = navigator.appVersion;
let isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;
let isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if (isIOS) {
return 0;
}
if (isAndroid) {
return 1;
}
return 2;
}
复制代码
/**
* @param { function } func
* @param { number } wait 延迟执行毫秒数
* @param { boolean } immediate true 表立即执行,false 表非立即执行
*/
export function debounce(func,wait,immediate) {
let timeout;
return function () {
let context = this;
let args = arguments;
if (timeout) clearTimeout(timeout);
if (immediate) {
let callNow = !timeout;
timeout = setTimeout(() => {
timeout = null;
}, wait);
if (callNow) func.apply(context, args)
}
else {
timeout = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
}
复制代码
/**
* @param { function } func 函数
* @param { number } wait 延迟执行毫秒数
* @param { number } type 1 表时间戳版,2 表定时器版
*/
export function throttle(func, wait ,type) {
let previous, timeout;
if(type===1){
previous = 0;
}else if(type===2){
timeout = null;
}
return function() {
let context = this;
let args = arguments;
if(type===1){
let now = Date.now();
if (now - previous > wait) {
func.apply(context, args);
previous = now;
}
}else if(type===2){
if (!timeout) {
timeout = setTimeout(() => {
timeout = null;
func.apply(context, args)
}, wait)
}
}
}
}
复制代码
/**
* @param {*} target
*/
export function type(target) {
let ret = typeof(target);
let template = {
"[object Array]": "array",
"[object Object]":"object",
"[object Number]":"number - object",
"[object Boolean]":"boolean - object",
"[object String]":'string-object'
};
if(target === null) {
return 'null';
}else if(ret == "object"){
let str = Object.prototype.toString.call(target);
return template[str];
}else{
return ret;
}
}
复制代码
/**
* @param { number } min
* @param { number } max
*/
export const RandomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
复制代码
/**
* @param {array} arr
*/
export function arrScrambling(arr) {
let array = arr;
let index = array.length;
while (index) {
index -= 1;
let randomIndex = Math.floor(Math.random() * index);
let middleware = array[index];
array[index] = array[randomIndex];
array[randomIndex] = middleware
}
return array
}
复制代码
/**
* @param { array} arr1
* @param { array } arr2
*/
export const similarity = (arr1, arr2) => arr1.filter(v => arr2.includes(v));
复制代码
/**
* @param { array } arr
* @param {*} value
*/
export function countOccurrences(arr, value) {
return arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
}
复制代码
/**
* @param { number } arg1
* @param { number } arg2
*/
export function add(arg1, arg2) {
let r1, r2, m;
try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
m = Math.pow(10, Math.max(r1, r2));
return (arg1 * m + arg2 * m) / m
}
复制代码
/**
* @param { number } arg1
* @param { number } arg2
*/
export function sub(arg1, arg2) {
let r1, r2, m, n;
try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
m = Math.pow(10, Math.max(r1, r2));
n = (r1 >= r2) ? r1 : r2;
return Number(((arg1 * m - arg2 * m) / m).toFixed(n));
}
复制代码
/**
* @param { number } num1
* @param { number } num2
*/
export function division(num1,num2){
let t1,t2,r1,r2;
try{
t1 = num1.toString().split('.')[1].length;
}catch(e){
t1 = 0;
}
try{
t2=num2.toString().split(".")[1].length;
}catch(e){
t2=0;
}
r1=Number(num1.toString().replace(".",""));
r2=Number(num2.toString().replace(".",""));
return (r1/r2)*Math.pow(10,t2-t1);
}
复制代码
/**
* @param { number } num1
* @param { number } num2
*/
export function mcl(num1,num2){
let m=0,s1=num1.toString(),s2=num2.toString();
try{m+=s1.split(".")[1].length}catch(e){}
try{m+=s2.split(".")[1].length}catch(e){}
return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m);
}
复制代码
/**
* @param { function } f
*/
export function tco(f) {
let value;
let active = false;
let accumulated = [];
return function accumulator() {
accumulated.push(arguments);
if (!active) {
active = true;
while (accumulated.length) {
value = f.apply(this, accumulated.shift());
}
active = false;
return value;
}
};
}
复制代码
export function randomNumInteger(min, max) {
switch (arguments.length) {
case 1:
return parseInt(Math.random() * min + 1, 10);
case 2:
return parseInt(Math.random() * (max - min + 1) + min, 10);
default:
return 0
}
}
复制代码
/**
* @param { string } str 待处理字符串
* @param { number } type 去除空格类型 1-所有空格 2-前后空格 3-前空格 4-后空格 默认为1
*/
export function trim(str, type = 1) {
if (type && type !== 1 && type !== 2 && type !== 3 && type !== 4) return;
switch (type) {
case 1:
return str.replace(/\s/g, "");
case 2:
return str.replace(/(^\s)|(\s*$)/g, "");
case 3:
return str.replace(/(^\s)/g, "");
case 4:
return str.replace(/(\s$)/g, "");
default:
return str;
}
}
复制代码
/**
* @param { string } str 待转换的字符串
* @param { number } type 1-全大写 2-全小写 3-首字母大写 其他-不转换
*/
export function turnCase(str, type) {
switch (type) {
case 1:
return str.toUpperCase();
case 2:
return str.toLowerCase();
case 3:
return str[0].toUpperCase() + str.substr(1).toLowerCase();
default:
return str;
}
}
复制代码
/**
* 方法一
*/
export function hexColor() {
let str = '#';
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F'];
for (let i = 0; i < 6; i++) {
let index = Number.parseInt((Math.random() * 16).toString());
str += arr[index]
}
return str;
}
复制代码
/**
* 方法二
*/
export const randomHexColorCode = () => {
let n = (Math.random() * 0xfffff * 1000000).toString(16);
return '#' + n.slice(0, 6);
};
复制代码
export const escapeHTML = str =>{
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
);
};
复制代码
export const detectDeviceType = () => { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop'; };
复制代码
/**
* 例: hide(document.querySelectorAll('img'))
*/
export const hideTag = (...el) => [...el].forEach(e => (e.style.display = 'none'));
复制代码
/**
* @param { element} el 元素节点
* @param { string } ruleName 指定元素的名称
*/
export const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
复制代码
/**
* @param { element } parent
* @param { element } child
* 例:elementContains(document.querySelector('head'), document.querySelector('title')); // true
*/
export const elementContains = (parent, child) => parent !== child && parent.contains(child);
复制代码
/**
* @param { number } val 输入的数字
* @param { number } maxNum 数字规定界限
*/
export const outOfNum = (val, maxNum) =>{
val = val ? val-0 :0;
if (val > maxNum ) {
return `${maxNum}+`
}else{
return val;
}
};
复制代码
const hide = (el) => Array.from(el).forEach(e => (e.style.display = 'none'));
// 事例:隐藏页面上所有``元素?
hide(document.querySelectorAll('img'))
复制代码
页面DOM里的每个节点上都有一个classList对象,程序员可以使用里面的方法新增、删除、修改节点上的CSS类。使用classList,程序员还可以用它来判断某个节点是否被赋予了某个CSS类。
const hasClass = (el, className) => el.classList.contains(className)
// 事例
hasClass(document.querySelector('p.special'), 'special') // true
复制代码
const toggleClass = (el, className) => el.classList.toggle(className)
// 事例 移除 p 具有类`special`的 special 类
toggleClass(document.querySelector('p.special'), 'special')
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});
// 事例
getScrollPosition(); // {x: 0, y: 200}
复制代码
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
}
// 事例
scrollToTop()
复制代码
window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行。
requestAnimationFrame:优势:由系统决定回调函数的执行时机。60Hz的刷新频率,那么每次刷新的间隔中会执行一次回调函数,不会引起丢帧,不会卡顿。
window.requestAnimationFrame() 告诉浏览器——你希望执行一个动画,并且要求浏览器在下次重绘之前调用指定的回调函数更新动画。该方法需要传入一个回调函数作为参数,该回调函数会在浏览器下一次重绘之前执行。
requestAnimationFrame:优势:由系统决定回调函数的执行时机。60Hz的刷新频率,那么每次刷新的间隔中会执行一次回调函数,不会引起丢帧,不会卡顿。
复制代码
const elementContains = (parent, child) => parent !== child && parent.contains(child);
// 事例
elementContains(document.querySelector('head'), document.querySelector('title'));
// true
elementContains(document.querySelector('body'), document.querySelector('body'));
// false
复制代码
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
// 事例
elementIsVisibleInViewport(el); // 需要左右可见
elementIsVisibleInViewport(el, true); // 需要全屏(上下左右)可以见
复制代码
const getImages = (el, includeDuplicates = false) => {
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
return includeDuplicates ? images : [...new Set(images)];
};
// 事例:includeDuplicates 为 true 表示需要排除重复元素
getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
getImages(document, false); // ['image1.jpg', 'image2.png', '...']