常用js函数

//JS把全角转为半角的函数  
function CtoH(str)  
{  
    var result="";  
    for (var i = 0; i < str.length; i++){  
        if (str.charCodeAt(i)==12288){  
            result+= String.fromCharCode(str.charCodeAt(i)-12256);  
            continue;  
        }
        if (str.charCodeAt(i)>65280 && str.charCodeAt(i)<65375) {
            result+= String.fromCharCode(str.charCodeAt(i)-65248);  
        } else {
            result+= String.fromCharCode(str.charCodeAt(i));  
        }  
    }  
    return result;  
} 

// 节流公共函数
function debounce(func, wait = 200, immediate = false) {
  let timeout, args, context, timestamp, result

  const later = function() {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function(...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

//  时间戳格式转换函数
function parseTime(time, cFormat = '{y}-{m}-{d} {h}:{i}:{s}') {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

// 百度地图 api引入函数
function BMPGL(ak) {
  return new Promise(function(resolve, reject) {
    window.MapJsInit = function() {
      // eslint-disable-next-line
      resolve(BMapGL)
    }
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `http://api.map.baidu.com/api?v=1.0&type=webgl&ak=${ak}&callback=MapJsInit`
    script.onerror = reject
    document.head.appendChild(script)
  })
}

// 深拷贝函数
function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}
//  压缩图片函数 
function compressImg (file, limit = 512000) {   //  limit要压缩到多大以下,这里默认500k
  if (file.size > 1024 * 1024 * 10) {
    //  默认不能传大于10M的图片
    return {code: 500, msg: '图片大于10M,请选择小于10M的图片'}
  } else if (file.size < limit) {
    return {code: 200, data: file}
  } else {
    return new Promise((resolve, reject) => {
      let turl = null
      let timg = new Image()
      turl = window.URL.createObjectURL(file)
      timg.src = turl
      timg.onload = async function () {
        let tmpImg = await compare(timg, limit)
        let tfile = dataURLtoFile(tmpImg.src, 'picture.png') //  这里依赖下边的函数,将base64转成文件,因为传入的是文件
        resolve({code: 200, data: tfile})
      }
    })
  }
  function compare (img, limit) { // 递归函数,只要不小于限制值就继续压缩
    let tsrc = comp(img)
    let timg = new Image()
    timg.src = tsrc
    return new Promise((resolve, reject) => {
      timg.onload = async function () {
        timg.size = Math.ceil(tsrc.length * 0.76)
        if (timg.size > limit) {
          resolve(compare(timg, limit))
        } else {
          resolve(timg)
        }
      }
    })
  }
  function comp (img) {
    let twidth = img.width * 0.9
    let theight = img.height * 0.9
    if (twidth > 900) {
      twidth = 900
      theight = img.height / img.width * 900
    }
    let tcan = document.createElement('canvas')
    tcan.setAttribute('width', twidth)
    tcan.setAttribute('height', theight)
    let ctx = tcan.getContext('2d')
    ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, twidth, theight)
    return tcan.toDataURL('image/png')
  }
}
// 复制图片函数,图片包含的一些信息,(比如ps痕迹等),可通过复制删除
 function copyImg (ele) {
        // 检测文件类型
        let file = ele.files[0]
        let extendName = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase()
        if (extendName != 'jpg' && extendName != 'png' && extendName != 'jpeg' && extendName != 'bmp') {
          alert('请上传图片文件')
          ele.value = ''
          return
        }
        // 开始复制
        let img = new Image()
        img.onload = () => {
          let canvas = document.createElement('canvas')
          canvas.width = img.width
          canvas.height = img.height
          let ctx = canvas.getContext('2d')
          ctx.drawImage(img, 0, 0)
          canvas.toBlob(blob => {
            let ta = document.createElement('a')
            ta.href = window.URL.createObjectURL(blob)
            ta.download = 'newPicture.png'
            ta.click()
          })
          
        }
        img.src = window.URL.createObjectURL(file)
 }
//  base64 转文件函数
function dataURLtoFile(dataurl, filename) {
  // 将base64转换为文件,dataurl为base64字符串,filename为文件名(必须带后缀名,如.jpg,.png)
  var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
      bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], filename, {type:mime});
}

//  检查图片是否为方形
function checkIsRect (file, allow = 0) { // allow是容差,看起来是方形还是绝对是方形,单位像素
  if ((file.type && file.type.startsWith('image')) || (file.name && (file.name.endsWith('.jpg') || file.name.endsWith('.png') || file.name.endsWith('.jpeg')))) {
    return new Promise((resolve, reject) => {
      let turl = window.URL.createObjectURL(file)
      let timg = new Image()
      timg.onload = () => {
        if (Math.abs(timg.width - timg.height) > allow) {
          resolve(false)
        } else {
          resolve(true)
        }
      }
      timg.src = turl
    })
  } else {
    return false
  }
}

// 兼容的videoDom对象申请全屏显示api
function toFullVideo(){
  if(videoDom.requestFullscreen){
    return videoDom.requestFullscreen();
  }else if(videoDom.webkitRequestFullScreen){
    return videoDom.webkitRequestFullScreen();
  }else if(videoDom.mozRequestFullScreen){
    return videoDom.mozRequestFullScreen();
  }else{
    return videoDom.msRequestFullscreen();
  }
}

单行获取指定名字的cookie

const cookie = name => `; ${document.cookie}`.split(`; ${name}=`).pop().split(';').shift();
    
cookie('_ga');

单行rgb颜色转16进制颜色

const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
 //  <<  位操作符,有符号左移
rgbToHex(0, 51, 255); 

单行代码 把文本写入剪切板

const copyToClipboard = (text) => navigator.clipboard.writeText(text);
    
copyToClipboard("Hello World");

生成随机 十六进制颜色

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
    
 console.log(randomHex());

获取用户选择的文本

const getSelectedText = () => window.getSelection().toString();
    
getSelectedText();

检测用户设备是否处于暗夜模式

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
    
console.log(isDarkMode) 

对象的Array 根据某个key排序

// 按照某个key排序, desc 是否 正序  
function sortObj (arr, key, desc = false) {
  let tkey = 1
  if (desc) { tkey = -1 }
  arr.sort((a, b)=> {
    if (a[key] > b[key]) {
      return tkey
    } else if (a[key] < b[key]) {
      return -1 * tkey
    } else {
      return 0
    }
  })
}

取出一个数组的所有集合,列出集合

// 一个数组取出n 个不重复的数有几种取法,【性能不咋地】
function getRandomN (ar, n) {
  let arr = Object.assign([], ar)
  let tmpar = arr.map(item => [item])
  if (arr.length <= n) { return [arr.join(' ')] }
  if (n == 1) {return arr}

  let m = 1
  let tar = []
  let length = tmpar.length
  while (m < n) {
    while(tmpar.length) {
      let tj = tmpar.shift()
      for (let i=0;i item.length == m)
    
    length = tmpar.length
    tar = []
  }
  tmpar.forEach(item => item.sort())
  let tret = Array.from(new Set(tmpar.map(item =>item.join(' '))))
  return tret
}

监听浏览器复制事件 、粘贴事件

document.addEventListener('copy', function(e){
      console.log(e.clipboardData, window.clipboardData)
    })
    document.addEventListener('paste', function(e){
      console.log(e.clipboardData.getData('Text'))
    })

你可能感兴趣的:(常用js函数)