日常小工具函数合集

298 阅读1分钟

拷贝文案

    	copyText(text = '') {
		const input = document.createElement('input');
		//  改成只读,禁止用户输入法自动获取焦点(兼容 IOS)
		input.setAttribute('readonly', 'readonly');
        input.setAttribute('value', text);
		document.body.appendChild(input);
		// 人为的设置选中全部文案(兼容 ios)
		input.select();
		input.setSelectionRange(0, 9999);
		const copyResValue = document.execCommand('copy');
		// 清除元素
        document.body.removeChild(input);
		return copyResValue;
	},

简单的数字格式划

.toLocaleString('en-US')
// (12333386).toLocaleString('en-US') 12,333,386

模拟用户调整浏览器

window.dispatchEvent(new Event('resize'))

返回随机字符串

    	function getRandomStr(len, prefix = '') {
		let text = '', prefixLen = prefix ? prefix.length : 0;
		const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
		for (let i = 0; i < len - prefixLen; i++) {
			text += possible.charAt(Math.floor(Math.random() * possible.length));
		}
		return prefix + text;
	}