utils

/**
 * 是否是數(shù)字
 * @param {any} n
 */
export const validateNumber = (n: any) =>
  !isNaN(parseFloat(n)) && isFinite(n) && Number(n) === n

/**
 * 保留兩位小數(shù)、千分位格式化,格式:12,345.67
 * @param {string|number} amount
 * @returns {string}
 */
export const formatAmount = (amount: any) => {
  if (!validateNumber(+amount)) {
    return amount
  }
  return (+amount).toFixed(2).replace(/\d{1,3}(?=(\d{3})+(\.\d*)?$)/g, '$&,')
}



// 刪除url中某個(gè)參數(shù)
const funcUrlDel = (loca, name) => {
  let baseUrl = ''
  if (loca.indexOf('&') > -1) {
    baseUrl = loca.split('?')[0] + '?'
  } else {
    baseUrl = loca.split('?')[0]
  }
  let query = loca.split('?')[1]
  if (query && query.indexOf(name) > -1) {
    var obj = {}
    var arr = query.split('&')
    for (var i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')
      obj[arr[i][0]] = arr[i][1]
    }
    delete obj[name]
    var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g, '').replace(/\:/g, '=').replace(/\,/g, '&')
    return url
  } else {
    return loca
  }
}




/**
 * 獲取Url參數(shù)中指定name的值
 * @param name 參數(shù)名稱
 * @returns {string}
 */
export const getURLParam = (name: string) => {
  const re = new RegExp('(^|&)' + name + '=([^&#]*)(&|$)')
  let value = ''
  const arrHash = window.location.hash.split('?')
  const arrSearch = window.location.search.substr(1).split('?')
  arrHash.shift()
  const arr = arrSearch.concat(arrHash)

  for (let i = 0; i < arr.length; i++) {
    const r = arr[i].match(re)
    if (r !== null && r[2]) {
      value = r[2]
      break
    }
  }
  return value
}

###  延時(shí)函數(shù)
export const sleep = function(delay: number) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      try {
        resolve(1)
      } catch (e) {
        reject(0)
      }
    }, delay)
  })
}
/**
 * rem 換算 px
 * @param rem 設(shè)計(jì)稿rem值
 * @returns {number} px值
 */
export const rem2px = (rem: any) => {
  const rootFontSize = parseFloat(
    window.document.documentElement.style.fontSize
  )
  return parseFloat(rem) * rootFontSize
}

平滑滾動(dòng)

const scrollToTop = ()  => {
       const c = document.documentElement.scrollTop || document.body.scrollTop;
        if (c > 0) {
          window.requestAnimationFrame(scrollToTop);
          window.scrollTo(0, c - c / 8);
        }
    }

正則去掉括號(hào)

cosnt nstr = str.replace(/\([^\)]*\)/g,"")

  • js編譯、解析Urlencode
1、編碼
var str  = encodeURIComponent('中文');
2、解碼
var str  = decodeURIComponent(UrlEncode);

替換中文逗號(hào)

    this.skuIds = this.skuIds.replace(/,/ig,',')

移動(dòng)端彈窗去掉滾動(dòng)條

public onShowChange(value: boolean) {
    if (value) {
      document.documentElement.style.position = 'fixed'
      document.body.style.overflow = 'hidden'
      document.body.addEventListener(
        'touchmove',
        event => {
          event.preventDefault()
        },
        false
      )
    } else {
      document.documentElement.style.position = 'static'
      document.body.style.overflow = 'auto'
      document.body.removeEventListener(
        'touchmove',
        event => {
          event.preventDefault()
        },
        false
      )
    }


### 下載
handleFileStreamExcel(res, fileName) {
      const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 創(chuàng)建下載的鏈接
      downloadElement.href = href
      downloadElement.download = fileName + '.xlsx' // 下載后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 點(diǎn)擊下載
      document.body.removeChild(downloadElement) // 下載完成移除元素
      window.URL.revokeObjectURL(href) // 釋放掉blob對(duì)象
    },
    handleFileStreamCsv(res, fileName) {
      const blob = new Blob([res], { type: 'text/csv' })
      const downloadElement = document.createElement('a')
      const href = window.URL.createObjectURL(blob) // 創(chuàng)建下載的鏈接
      downloadElement.href = href
      downloadElement.download = fileName + '.csv' // 下載后文件名
      document.body.appendChild(downloadElement)
      downloadElement.click() // 點(diǎn)擊下載
      document.body.removeChild(downloadElement) // 下載完成移除元素
      window.URL.revokeObjectURL(href) // 釋放掉blob對(duì)象
    }

兼容安卓input喚起鍵盤

(function (window,document) {
    document.querySelector('input[type="text"]').addEventListener('focus',function (e) {
     setTimeout(function () {
         var docHeight = window.innerHeight;
         var bottom = e.target.getBoundingClientRect().bottom
         var scrollHeight = bottom-docHeight
         if(scrollHeight>0){
             document.body.scrollTop =  scrollHeight+document.body.scrollTop+10
         }
     },400)
    },false)
})(window,document)

判斷當(dāng)前是安卓設(shè)備還是ios

const u = navigator.userAgent
// 安卓
export const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
// IOS
export const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

/**

  • 兼容安卓鍵盤
    */
export const androidKeyboardInit = () => {
  const u = navigator.userAgent
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
  if (isAndroid) {
    document.querySelector('input[type="text"],input[type="password"]').addEventListener('focus', function (e) {
      setTimeout(function () {
        var docHeight = window.innerHeight
        var bottom = e.target.getBoundingClientRect().bottom
        var scrollHeight = bottom - docHeight
        if (scrollHeight > 0) {
          document.body.scrollTop = scrollHeight + document.body.scrollTop + 10
        }
      }, 400)
    }, false)
  }
}


/**
 * 兼容安卓鍵盤
 */
export const androidKeyboardInit = () => {
  const u = navigator.userAgent
  const isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
  if (isAndroid) {
    window.addEventListener('resize', () => {
      const activeElement = document.activeElement
      if (activeElement.tagName === 'INPUT' ||
          activeElement.tagName === 'TEXTAREA') {
        setTimeout(() => {
          activeElement.scrollIntoView()
        }, 100)
      }
    })
  }
}

pc跳轉(zhuǎn)移動(dòng)端

if( window.location.search.indexOf("?via=")<0 &&
                ( /Android|Windows Phone|iPhone|iPod/i.test(navigator.userAgent)  || /AppleWebKit.*Mobile/i.test(navigator.userAgent) )
          ){
                try{
                    if(/Android|iPhone|Windows Phone|webOS|iPod|BlackBerry/i.test(navigator.userAgent)){
                        var referrer = document.referrer;
                        if (referrer && referrer !== "") {
                          referrer += referrer.indexOf("?") > -1 ? "&pcjump=1" : "?pcjump=1";
                        } else {
                          referrer = "none";
                        }
                        if (document.cookie) {
                          var date = new Date();
                          date.setDate(date.getDate() + 1);
                          document.cookie = "PC2MRealRef=" + escape(referrer) + ";expires=" + date.toUTCString() + "; domain=.zol.com.cn; path=/";
                        }
                        window.location.href="xxx/mobile/";
                    }
                }catch(e){}

解析excel 流文件 攔截器參數(shù)配置 responseType: 'blob'

function downLoadxlsx (excelTitle = 1, blobData = '') {
      if (!blobData) return false
      const url = window.URL.createObjectURL(new Blob([blobData], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', excelTitle + '.xlsx')
      document.body.appendChild(link)
      link.click()
    }

// 對(duì)象去重
    Array.prototype.unique = function (key = '') {
      const arr = this || []
      if (!arr || !arr.length) return []
      let newArr = []
      arr.forEach(item => {
        const filterLists = newArr.filter(ele => {
          return ele[key] === item[key]
        })
        if (filterLists && !filterLists.length) newArr.push(item)
      })
      return newArr
    }
// 統(tǒng)計(jì)數(shù)量
Array.prototype.statistics = function () {
      const _arr = this || []
      return _arr.reduce((result, item) => {
        result[item] = result.hasOwnProperty(item) ? ++result[item] : 1
        return result
      }, {})
    }
// 取最大的對(duì)象
Array.prototype.maxNum = function () {
      const _arr = this || []
      const _obj = _arr.reduce((result, item) => {
        result[item] = result.hasOwnProperty(item) ? ++result[item] : 1
        return result
      }, {})
      const key = Object.keys(_obj).find(
        item => Math.max(...Object.values(_obj)) === _obj[item]
      )
      return { label: key, num: _obj[key] }
    }


export const to = (promise) => {
  return promise
    .then(data => [data, null])
    .catch(err => [undefined, err])
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容