JS常用的工具函数
前言
随着项目的积累,将平时用到的函数做了总结,抽出了日常用到的工具函数,仅供大家参考,有问题还望指正,谢谢大家。
一、动态引入js
export const injectScript = (src) => {
const s = document.createElement('script')
s.type = 'text/javascript'
s.async = true
s.src = src
const t = document.getElementsByTagName('script')[0]
t.parentNode.insertBefore(s, t)
}
二、url地址下载
export const download = (url) => {
const isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1
const isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1
if (isChrome || isSafari) {
const link = document.createElement('a')
link.href = url
if (link.download !== undefined) {
const fileName = url.substring(url.lastIndexOf('/') + 1, url.length)
link.download = fileName
}
if (document.createEvent) {
const e = document.createEvent('MouseEvents')
e.initEvent('click', true, true)
link.dispatchEvent(e)
return true
}
}
if (url.indexOf('?') === -1) {
url += '?download'
}
window.open(url, '_self')
return true
}
三、class增、删、查
// el是否包含某个class
export const hasClass = (el, className) => {
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
return reg.test(el.className)
}
// el添加某个class
export const addClass = (el, className) => {
if (hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
}
// el去除某个class
export const removeClass = (el, className) => {
if (!hasClass(el, className)) {
return
}
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)', 'g')
el.className = el.className.replace(reg, ' ')
}
四、随机数
export const random = (min, max) => {
if (arguments.length === 2) {
return Math.floor(min + Math.random() * ((max + 1) - min))
} else {
return null
}
}
五、数字计算
export const max = (arr) => { // 最大值
return Math.max.apply(null, arr)
}
export const min = (arr) => { // 最小值
return Math.min.apply(null, arr)
}
export const sum = (arr) => { // 求和
return arr.reduce((pre, cur) => {
return pre + cur
})
}
export const average = (arr) => { // 平均值
return sum(arr) / arr.length
}
六、去除空格
export const trim = (str, type) => {
type = type || 1
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
}
}
七、随机生成颜色
1.十六进制格式(#000000 - #FFFFFF)
// 随机生成十六进制颜色
export const randomHexColor = () => {
var hex = Math.floor(Math.random() * 16777216).toString(16) // 生成ffffff以内16进制数
while (hex.length < 6) { // while循环判断hex位数,少于6位前面加0凑够6位
hex = '0' + hex
}
return '#' + hex // 返回‘#'开头16进制颜色
}
2.RGBA格式
// 随机生成RGBA颜色
export const randomRgbaColor = () => {
var r = Math.floor(Math.random() * 256); // 随机生成256以内r值
var g = Math.floor(Math.random() * 256); // 随机生成256以内g值
var b = Math.floor(Math.random() * 256); // 随机生成256以内b值
var alpha = Math.random(); //随机生成1以内a值
return `rgb(${r},${g},${b},${alpha})`; //返回rgba(r,g,b,a)格式颜色
}