美文网首页
js通用方法封装

js通用方法封装

作者: Cola_Mr | 来源:发表于2023-08-07 15:01 被阅读0次

    js获取URL上的参数

    export function queryURLParams(url) {
      try {
        if (!url) {
          url = String(window.location)
        }
        // str为?之后的参数部分字符串
        const str = url.substr(url.indexOf('?') + 1)
        // arr每个元素都是完整的参数键值
        const arr = str.split('&')
        // result为存储参数键值的集合
        const result = {}
        for (let i = 0; i < arr.length; i++) {
          // item的两个元素分别为参数名和参数值
          const item = arr[i].split('=')
          result[item[0]] = item[1]
        }
        return result
      } catch (err) {
        console.error(err);
        return null
      }
    }
    

    js计算文件MD5码

    import SparkMD5 from 'spark-md5'
    export default function (file) {
      return new Promise(resolve => {
        const fileReader = new FileReader()
        const spark = new SparkMD5.ArrayBuffer()
        // 获取文件二进制数据
        fileReader.readAsArrayBuffer(file)
        fileReader.onload = function (e) {
          spark.append(e.target.result)
          const md5 = spark.end()
          resolve(md5)
        }
      })
    }
    

    js读取文本文件中的内容

    export default function (file) {
      return new Promise(resolve => {
        const reader = new FileReader()
        reader.readAsText(file, 'UTF-8')
        reader.onload = (e) => {
          resolve(e)
        }
      }).catch(err => {
        throw err
      })
    }
    

    js读取外网音频,获取音频对象实例(如:得到音频时长)

    export default function (src) {
      return new Promise(resolve => {
        const audioObj = document.createElement('audio')
        audioObj.src = src
        audioObj.load()
        audioObj.onloadedmetadata = function (evt) {
          // 执行上传的方法,获取外网路径,上传进度等
          resolve(audioObj)
        }
      }).catch(err => {
        Error(err)
        return null
      })
    }
    

    js获取图片文件的实例对象

    export default function (file) {
      return new Promise(resolve => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = function (evt) {
          var replaceSrc = evt.target.result
          var imageObj = new Image()
          imageObj.src = replaceSrc
          imageObj.onload = function () {
            resolve(imageObj)
          }
        }
      }).catch(err => {
        Error(err)
        return null
      })
    }
    

    js获取视频文件的实例对象 (如:得到视频时长)

    export default function (file) {
      return new Promise(resolve => {
        const videoUrl = URL.createObjectURL(file)
        const videoObj = document.createElement('video')
        videoObj.src = videoUrl
        videoObj.load()
        videoObj.onloadedmetadata = function (evt) {
          URL.revokeObjectURL(videoUrl)
          resolve(videoObj)
        }
      }).catch(err => {
        Error(err)
        return null
      })
    }
    

    input选择文件

    export default function (fileType = '*', multiple = false) {
      return new Promise(resolve => {
        if (!fileType) throw new Error('The file type needs to be specified')
        const input = document.createElement('input')
        input.setAttribute('type', 'file')
        input.setAttribute('accept', fileType)
        if (multiple) {
          input.setAttribute('multiple', 'multiple')
        }
        input.onchange = (e) => {
          resolve(e)
          input.remove()
        }
        input.click()
      }).catch(err => {
        throw err
      })
    }
    

    js图片压缩

    import ImageCompressor from 'js-image-compressor'
    
    export default function (file, maxWidth, maxHeight) {
      return new Promise((resolve,reject) => {
        new ImageCompressor({
          file: file,
          quality: 0.8,
          maxWidth,
          maxHeight,
          convertSize: 1000000,
          redressOrientation: false,
          success: function (result) {
            resolve(new File([result], result.name ? result.name : Date.now() + '.png', {
              type: result.type ? result.type : 'image/png',
              lastModified: Date.now()
            }))
          },
          error (e) {
            reject(e)
          }
        })
      }).catch(err => {
        throw err
      })
    }
    

    js截取视频封面

    export default function (file) {
      return new Promise(function (resolve, reject) {
        let data = '';
        const video = document.createElement("video");
        video.setAttribute('crossOrigin', 'anonymous');//处理跨域
        video.setAttribute('src', URL.createObjectURL(file));
        video.setAttribute('width', 400);
        video.setAttribute('height', 240);
        video.setAttribute('preload', 'auto');
        video.addEventListener('loadeddata', function () {
          const canvas = document.createElement("canvas"),
          width = video.width, //canvas的尺寸和图片一样
          height = video.height;
          canvas.width = width;
          canvas.height = height;
          canvas.getContext("2d").drawImage(video, 0, 0, width, height); //绘制canvas
          canvas.toBlob(function (e) {
            const file = new File([e], Date.now() + '.png', {
              type: e.type ? e.type : 'image/png',
              lastModified: Date.now()
            })
            resolve(file)
            video.remove()
            canvas.remove()
          }, 'image/png', 1)
        });
      })
    }
    

    js获取设备局域网IP地址

    export default function getLocalhostIP() {
      return new Promise((resolve, reject) => {
        var RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
        if (RTCPeerConnection) (function () {
          var rtc = new RTCPeerConnection({ iceServers: [] });
          if (1 || window.mozRTCPeerConnection) {
            rtc.createDataChannel('', { reliable: false });
          };
    
          rtc.onicecandidate = function (evt) {
            if (evt.candidate) grepSDP("a=" + evt.candidate.candidate);
          };
          rtc.createOffer(function (offerDesc) {
            grepSDP(offerDesc.sdp);
            rtc.setLocalDescription(offerDesc);
          }, function (e) { console.warn("offer failed", e); });
    
    
          var addrs = Object.create(null);
          addrs["0.0.0.0"] = false;
          function updateDisplay(newAddr) {
            if (newAddr in addrs) return;
            else addrs[newAddr] = true;
            var displayAddrs = Object.keys(addrs).filter(function (k) { return addrs[k]; });
            for (var i = 0; i < displayAddrs.length; i++) {
              if (displayAddrs[i].length > 16) {
                displayAddrs.splice(i, 1);
                i--;
              }
            }
            resolve(displayAddrs[0])
          }
    
          function grepSDP(sdp) {
            var hosts = [];
            sdp.split('\r\n').forEach(function (line, index, arr) {
              if (~line.indexOf("a=candidate")) {
                var parts = line.split(' '),
                  addr = parts[4],
                  type = parts[7];
                if (type === 'host') updateDisplay(addr);
              } else if (~line.indexOf("c=")) {
                var parts = line.split(' '),
                  addr = parts[2];
                updateDisplay(addr);
              }
            });
          }
        })();
      }).catch(error => {
        throw error
      })
    }
    

    vue捕获全局错误

    import axios from 'axios'
    
    export default async function (error, vm) {
        try {
            let errMSg = error.stack ? error.stack : JSON.stringify(error)
            if (vm && vm.$route) {
                const { fullPath, path, query, params } = vm.$route
                errMSg += '[route message]: ' + JSON.stringify({
                    fullPath: fullPath,
                    path: path,
                    query: query,
                    params: params
                })
            }
            const { data } = await axios.post('/exception_log', { exceptionTxt: errMSg })
            if (data.returnCode != 1) throw data
        } catch (err) {
            console.error('Failed to report the error log. The error log is below.', '--------->', err)
        }
        console.error('抛出全局异常');
        console.error(error);
    }
    
    // 捕获全局的错误
    Vue.config.errorHandler = errorHandler;
    Vue.prototype.$throw = (error) => errorHandler(error, this);
    window.onerror = function (message, source, line, column, error) {
      // do something
      errorHandler(error)
    };
    window.addEventListener('unhandledrejection', function (event) {
      event.preventDefault();
      errorHandler(event.reason)
    });
    

    js获取剪切板中的内容

    export default function navigatorClipboard () {
      return new Promise((resolve, reject) => {
        // 获取剪切板内的图片链接
        navigator.clipboard.readText().then((v) => {
          if (v) {
            resolve(v)
          } else {
            resolve(null)
          }
        }).catch((err) => {
          reject(err)
        })
      }).catch(err => {
        throw err
      })
    }
    

    请求参数hash签名计算

    export default function hashUtil (data) {
      const keys = Object.keys(data)
      keys.sort()
      const kvs = keys.map(key => key + '=' + data[key])
      console.log(kvs.join('&'))
      const md5 = crypto.createHash('md5')
      return md5.update(kvs.join('&')).digest('hex')
    }
    

    js复制文本

    export default function copyClick(text) {
          try {
            const el = document.createElement('input')
            el.setAttribute('value', text)
            document.body.appendChild(el)
            el.select()
            document.execCommand('copy')
            document.body.removeChild(el)
            alert('已复制')
            el.remove()
          } catch (err) {
            alert(err.message)
            throw err
          }
    }
    

    cookie操作

    class Cookies {
          set (name, value, day) {
              let oDate = new Date()
              oDate.setDate(oDate.getDate() + (day || 30))
               document.cookie = name.trim() + '=' + value.trim() + ';expires=' + oDate + ';path=/;'
          }
          get (name) {
              let str = document.cookie
              let arr = str.split(';')
              for (let i = 0; i < arr.length; i++) {
                  let newArr = arr[i].split('=')
                  if (newArr[0].trim() === name) {
                      return newArr[1]
                  }
              }
          }
          del (name) {
              this.set(name, '')
          }
    }
    

    获取元素距离页面顶部的距离

    function getDisTop(element) { 
        let realTop = element.offsetTop;
        let parent = element.offsetParent;
        while (parent) {
            realTop += parent.offsetTop;
            parent = parent.offsetParent;
        }
        return realTop;
      }
    

    计算图片上的颜色应该显示黑色还是白色

    export default function (imgEl) {
      var blockSize = 5, // only visit every 5 pixels
      defaultRGB = 'black', // for non-supporting envs
      canvas = document.createElement('canvas'),
      context = canvas.getContext && canvas.getContext('2d'),
      data, width, height,
      i = -4,
      length,
      rgb = {
          r: 0,
          g: 0,
          b: 0
      },
      count = 0;
    
      if (!context) {
        return defaultRGB;
      }
    
      height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
      width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
    
      context.drawImage(imgEl, 0, 0);
    
      try {
        data = context.getImageData(0, 0, width, height);
      } catch (e) {
        /* security error, img on diff domain */
        return defaultRGB;
      }
    
      length = data.data.length;
    
      while ((i += blockSize * 4) < length) {
        ++count;
        rgb.r += data.data[i];
        rgb.g += data.data[i + 1];
        rgb.b += data.data[i + 2];
      }
    
      // ~~ used to floor values
      rgb.r = ~~ (rgb.r / count);
      rgb.g = ~~ (rgb.g / count);
      rgb.b = ~~ (rgb.b / count);
      if ((rgb.r*0.299 + rgb.g*0.587 + rgb.b*0.114) > 186) {
        return 'black'
      } else {
        return 'white'
      }
    }
    

    Dom z-index获取最大的层获取

    export function getMaxZIndex() {
      let maxZIndex = 1000
      const els = document.querySelectorAll('body>*')
      for (let i = 0, len = els.length; i < len; i++) {
        const { zIndex } = window.getComputedStyle(els[i], null)
        if (!isNaN(zIndex) && zIndex && zIndex > maxZIndex) {
          maxZIndex = +zIndex
        }
      }
      return maxZIndex + 2
    }
    

    通过文件流下载

    export function downloadFile (data, fileName) {
      const a = document.createElement('a')
      document.body.appendChild(a)
      a.style = 'display: none'
      const blob = new Blob([data], {
        type: 'application/octet-stream'
      })
      const url = window.URL.createObjectURL(blob)
      a.href = url
      a.download = fileName
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
    }
    

    通过url进行下载

    export function downloadUrlFile (url, fileName) {
      const a = document.createElement('a')
      document.body.appendChild(a)
      a.style = 'display: none'
      a.href = url
      a.download = fileName
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
    }
    

    相关文章

      网友评论

          本文标题:js通用方法封装

          本文链接:https://www.haomeiwen.com/subject/uvegpdtx.html