常用的js 方法

75 阅读2分钟

格式化数据

10000000 -> 10,000,000

const formatCount = (count) => {return count.toLocaleString()}

图片转base64

async function imgUrl2Imgbase64(url: string): Promise<string | null> {
	return new Promise(resolve => {
		const image = new Image()
		image.src = url
		image.onload = () => {
			const canvas = document.createElement('canvas')
			canvas.width = image.naturalWidth
			canvas.height = image.naturalHeight
			canvas.style.width = `${canvas.width / window.devicePixelRatio}px`
			canvas.style.height = `${canvas.height / window.devicePixelRatio}px`
			const ctx = canvas.getContext('2d')
			if (!ctx) {
				return resolve(null)
			}
			ctx.drawImage(image, 0, 0)
			const base64 = canvas.toDataURL('image/png')

			return resolve(base64)
		}
		image.onerror = () => {
			resolve(null)
		}
	})
}

复制文字

function copyText(text: string): void {
        // @ts-ignore
	window.__ignoreEditorImgCopy = true //标记忽略编辑器图片选中拷贝

	const textElem = document.createElement('textarea')
	textElem.value = text
	textElem.style.width = '500px'
	textElem.style.position = 'absolute'
	textElem.style.left = '-10000000px'
	document.body.appendChild(textElem)
	textElem.select()
	document.execCommand('copy')
	textElem.remove()

	setTimeout(() => {
		// @ts-ignore
		window.__ignoreEditorImgCopy = false
	}, 0)
}

function copyHtml(ele: HTMLElement): void {
	// @ts-ignore
	window.__ignoreEditorImgCopy = true //标记忽略编辑器图片选中拷贝
	if (!ele) return
	ele.style.background = '#fff'
	ele.style.color = '#000'
	const range = document.createRange()
	range.selectNodeContents(ele)
	// eslint-disable-next-line no-unused-expressions
	window.getSelection()?.removeAllRanges()
	// eslint-disable-next-line no-unused-expressions
	window.getSelection()?.addRange(range)
	document.execCommand('copy')
	ele.removeAttribute('style')
	window.getSelection()?.removeAllRanges()
	setTimeout(() => {
		// @ts-ignore
		window.__ignoreEditorImgCopy = false
	}, 0)
}

全屏显示元素&退出全屏

//全屏显示
const 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();
  }
};

//退出全屏
const goExitFullscreen = () => {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.msExitFullscreen) {
    document.msExitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
};

获取数据类型

const getType = (value) => {
  const match = Object.prototype.toString.call(value).match(/ (\w+)]/)
  return match[1].toLocaleLowerCase()
}

getType() // undefined
getType({}}) // object
getType([]) // array
getType(1) // number
getType('fatfish') // string
getType(true) // boolean
getType(/fatfish/) // regexp

判断设备类型

const isMobile = () => {
  return !!navigator.userAgent.match(
    /(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
  );
};

const isAndroid = () => {
  return /android/i.test(navigator.userAgent.toLowerCase());
};

const isIOS = () => {
  let reg = /iPhone|iPad|iPod|iOS|Macintosh/i;
  return reg.test(navigator.userAgent.toLowerCase());
};

获取浏览器类型及其版本

const 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,
      };
};

生成随机长度的字符串

const 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;
};

randomString(10) // pfkMfjEJ6x
randomString(20) // ce6tEx1km4idRNMtym2S

选择文件

const isNull = (value) => {
  return getType(value) === 'null'
}

function webChooseFile(cb: (file: File) => unknown, accept?: string): void {
	const id = 'file_selector'
	let input = document.getElementById(id) as HTMLInputElement
	if (isNull(input)) {
		input = document.createElement('input')
		input.id = id
		input.type = 'file'
		input.style.position = 'fixed'
		input.style.left = '-100000px'
		document.body.appendChild(input)
	} else {
		input.value = ''
	}
	if (accept) {
		input.accept = accept
	} else {
		input.removeAttribute('accept')
	}
	input.onchange = (): void => {
		if (input.files?.length) {
			cb(input.files[0])
		}
	}
	input.classList.add('selectFile')
	const e = document.createEvent('MouseEvent') as unknown as Event
	e.initEvent('click', false, true)
	input.dispatchEvent(e)
}

function webMulChooseFile(cb: (file: FileList) => unknown, accept?: string): void {
	const id = 'file_selector_mul'
	let input = document.getElementById(id) as HTMLInputElement
	if (isNull(input)) {
		input = document.createElement('input')
		input.id = id
		input.type = 'file'
		input.multiple = true
		input.style.position = 'fixed'
		input.style.left = '-100000px'
		document.body.appendChild(input)
	} else {
		input.value = ''
	}
	if (accept) {
		input.accept = accept
	} else {
		input.removeAttribute('accept')
	}
	input.onchange = (): void => {
		if (input.files?.length) {
			cb(input.files)
		}
	}
	input.classList.add('selectFile')
	const e = document.createEvent('MouseEvent') as unknown as Event
	e.initEvent('click', false, true)
	input.dispatchEvent(e)
}