积累记录常用js工具方法,有新的好用的工具方法会持续更新记录。
1. 复制字符串
/**
* 拷贝字符串到剪切板
* @param value 字符串
*/
function copyString(value) {
const transfer = document.createElement('input');
document.body.appendChild(transfer);
transfer.value = value;
transfer.setSelectionRange(0, 9999999999);
transfer.focus();
transfer.select();
if (document.execCommand) {
document.execCommand('copy');
}
transfer.blur();
document.body.removeChild(transfer);
}
2. 下载base64为文件
/**
* 将base64下载为文件
* @param data base64数据
* @param filename 文件名
*/
function downloadBase64File(dataUrl, filename) {
const data = base64Img2Blob(dataUrl);
window.URL = window.URL || window.webkitURL;
const urlBlob = window.URL.createObjectURL(data);
const link = document.createElement('a');
link.style.display = 'none';
link.href = urlBlob;
const downloadFileName = filename;
link.setAttribute('download', downloadFileName);
document.body.appendChild(link);
link.click();
function base64Img2Blob(code) {
const parts = code.split(';base64,');
const contentType = parts[0].split(':')[1];
const raw = window.atob(parts[1]);
const rawLength = raw.length;
const uInt8Array = new Uint8Array(rawLength);
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
return new Blob([uInt8Array], { type: contentType });
}
}
3. 非递归搜索和处理树的节点
// 非递归搜索和处理节点
function search(tree, callback) {
if (callback(tree, null) === true) {
return current;
};
let array = [tree];
for (let i = 0; i < array.length; i++) {
const current = array[i];
if (current.children && current.children.length > 0) {
for (let j = 0; j < current.children.length; j++) {
const child = current.children[j];
if (callback(child, current) === true) {
return current;
};
array.push(child);
}
}
}
return null;
}
const tree = {
id: '1',
children: [
{
text: '子节点-11',
id: '11',
children: [
{
text: '子节点-111',
id: '111'
},
{
text: '子节点-112',
id: '112'
}
]
},
{
text: '子节点-12',
id: '12'
},
{
text: '子节点-13',
id: '13',
children: [
{
text: '子节点-131',
id: '131'
},
{
text: '子节点-132',
id: '132'
},
]
},
]
};
const result = search(tree, (node, parent) => {
// 在这里处理node...
console.log(node.id);
// 如果返回true则终止搜索
return node.id === '13';
});
console.log('search result:', result);
4. 判断js数据类型的万能方法
/**
* Object.prototype.toString.call封装的数据类型判断工具
* @method typeOf
* @param {Any} param 需要判断类型的参数
* @return {String} 小写类型字符串,例如"string" "array" "function"
*/
function typeOf(param) {
return Object.prototype.toString.call(param).slice(8, -1).toLowerCase();
}
5. 格式化时间
/**
* 格式化时间
* @method formatTime
* @param {Date} date 格式
* @param {String} formatStr 格式
* @return {String} fmt 格式化字符串
*/
function formatTime(date, formatStr) {
function format(date, t) {
var date = new Date(date);
var o = {
'M+': date.getMonth() + 1, // 月份
'd+': date.getDate(), // 日
'h+': date.getHours(), // 小时
'm+': date.getMinutes(), // 分
's+': date.getSeconds(), // 秒
'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
S: date.getMilliseconds() // 毫秒
};
if (/(y+)/.test(t)) {
t = t.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
}
for (var k in o) {
if (new RegExp('(' + k + ')').test(t)) {
t = t.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
}
}
return t;
}
if (typeof date === 'undefind') {
throw new Error('the param of function formatTime() can\'t be undefined');
}
if (typeof date === 'number') {
if (typeof formatStr === 'string') {
return format(date, formatStr);
}
return format(date, 'yyyy-MM-dd hh:mm:ss');
}
if (typeof date === 'string') {
date = (new Date(date)).getTime();
if (typeof formatStr === 'string') {
return format(date, formatStr);
}
return format(date, 'yyyy-MM-dd hh:mm:ss');
}
if (Object.prototype.toString.call(date) === '[object Date]') {
date = date.getTime();
if (typeof formatStr === 'string') {
return format(date, formatStr);
}
return format(date, 'yyyy-MM-dd hh:mm:ss');
}
}
6. 计算文本的高宽
/**
* 计算文本的高宽
* @param {String} text 文本
* @param {String} fontSize 字体大小
* @param {String} fontFamily 字体
* @return {Object} 高宽
*/
function getTextSize(text, fontSize, fontFamily) {
var span = document.createElement('div');
var result = {};
fontSize = fontSize || 14;
fontFamily = fontFamily || 'Microsoft YaHei';
result.width = span.offsetWidth;
result.height = span.offsetHeight;
span.setAttribute('style', `visibility: hidden;font-size: ${fontSize}px;font-family: ${fontFamily};display: inline-block;`);
document.body.appendChild(span);
if (typeof span.textContent !== 'undefined') {
span.textContent = text;
}
else {
span.innerText = text;
}
result.width = parseFloat(window.getComputedStyle(span).width) - result.width;
result.height = parseFloat(window.getComputedStyle(span).height) - result.height;
document.body.removeChild(span);
return result;
}
7. 16进制颜色与raba颜色互相转换
// 16进制转raba颜色
function hexToRGB (hex){
var sColor = hex.toLowerCase();
//十六进制颜色值的正则表达式
var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
// 如果是16进制颜色
if (sColor && reg.test(sColor)) {
if (sColor.length === 4) {
var sColorNew = "#";
for (var i=1; i<4; i+=1) {
sColorNew += sColor.slice(i, i+1).concat(sColor.slice(i, i+1));
}
sColor = sColorNew;
}
//处理六位的颜色值
var sColorChange = [];
for (var i=1; i<7; i+=2) {
sColorChange.push(parseInt("0x"+sColor.slice(i, i+2)));
}
return "rgb(" + sColorChange.join(",") + ")";
}
return sColor;
};
// raba颜色转16进制
function RGBToHex (color){
var values = color
.replace(/rgba?\(/, '')
.replace(/\)/, '')
.replace(/[\s+]/g, '')
.split(',')
var a = parseFloat(values[3] || 1),
r = Math.floor(a * parseInt(values[0]) + (1 - a) * 255),
g = Math.floor(a * parseInt(values[1]) + (1 - a) * 255),
b = Math.floor(a * parseInt(values[2]) + (1 - a) * 255)
return '#' +
('0' + r.toString(16)).slice(-2) +
('0' + g.toString(16)).slice(-2) +
('0' + b.toString(16)).slice(-2)
};