Skip to content

create 封装的一些创建函数

ts
/**
 * 生成随机数
 * @param min 最小值
 * @param max 最大值
 */
export function createRandomNum(min: number, max: number): number {
  return Math.floor(Math.random() * (max - min + 1)) + min
}
/**
 * 生成随机颜色
 * @param isRGB //true为rgb;false为十六进制
 */
export function createRandomColor(isRGB: boolean = false): string {
  const rgb = ['r', 'g', 'b']
  if (isRGB) {
    return `(${rgb.map(() => Math.floor(Math.random() * 256)).join(',')})`
  }
  return `#${rgb
    .map(() => Math.floor(Math.random() * 256).toString(16))
    .map(val => (val.length < 2 ? `0${val}` : val))
    .join('')}`
}
/**
 * 生成哈希
 * @param  hashLength 生成哈希长度
 */
export function createHash(hashLength: number): string {
  return Array.from(Array(hashLength || 24), () =>
    Math.floor(Math.random() * 36).toString(36)
  ).join('')
}
/**
 * 生成uuid
 */
export function createUuid(): string {
  const arr = []
  const baseStr = '0123456789abcdef'
  for (let i = 0; i < 36; i++) {
    arr.push(baseStr.substr(Math.floor(Math.random() * 16), 1))
  }
  arr[8] = '-'
  arr[13] = '-'
  arr[18] = '-'
  arr[23] = '-'
  return arr.join('')
}

/**
 * 创建input标签
 * @param key
 * @param val
 * @param type
 */
export function createInputElement(key: string, val: any, type: string = 'text'): HTMLInputElement {
  const input = document.createElement('input')
  input.type = type
  input.name = key
  input.value = val
  return input
}

/**
 * 创建表单标签(通过对象)
 * @param params
 */
export function createFormElement(params: { [x: string]: any }) {
  const form = document.createElement('form')
  // eslint-disable-next-line no-restricted-syntax
  for (const key in params) {
    if (Object.prototype.hasOwnProperty.call(params, key)) {
      const element = params[key]
      if (element instanceof File || element instanceof Blob) {
        form.appendChild(createInputElement(key, element, 'file'))
      } else {
        form.appendChild(createInputElement(key, element))
      }
    }
  }
  return form
}

/**
 * 创建表单发起的请求(不通过ajax)
 * @param param
 */
export function createFormRequest(param: {
  /** 提交地址 */
  url: string
  /** 提交方式 */
  method: 'get' | 'post'
  /** 编码方式 */
  contentType: 'multipart/form-data' | 'application/x-www-form-urlencoded' | 'text/plain'
  /** 提交数据 */
  data: { [x: string]: any }
  target: '_self' | '_blank' | '_parent' | '_top'
}) {
  const form = createFormElement(param.data)
  form.style.display = 'hidden'
  form.action = param.url
  form.enctype = param.contentType
  form.method = param.method
  form.target = param.target
  document.body.appendChild(form)
  form.submit()
  document.body.removeChild(form)
}

/**
 * 创建Mutation观察者对象
 * @param el
 * @param options
 * @param callback
 */
export function createMutationObserver(
  el: Element,
  options?: MutationObserverInit,
  callback?: (mutation: MutationRecord, observer: MutationObserver) => void
) {
  if (!el) {
    throw new Error('el is undefined')
  }
  const observer = new MutationObserver((mutations, _observer) => {
    mutations.forEach(mutation => {
      callback?.(mutation, _observer)
    })
  })
  observer.observe(el, options)
  return observer
}

/**
 * 创建尺寸观察者对象
 * @param el
 * @param cb
 */
export function createResizeObserver(el: Element, cb: ResizeObserverCallback) {
  if (!el) {
    throw new Error('el is undefined')
  }
  const observer = new ResizeObserver(cb)
  observer.observe(el)
  return observer
}