util.js

javascript

浏览数:198

2019-1-7


util.js

/**
* 若要配合axios,则需要在引入改js文件之前引入axios.js
*/

; (function (undefined) {
  "use strict"
  let _global;

  /**axios 拦截器 START */
  try {
    axios.defaults.headers.common = {
      'X-Requested-With': 'XMLHttpRequest',
    };
    //在请求头附带一些身份验证数据
    axios.defaults.headers['cookiekey'] = getKey('cookiekey');
  } catch (err) {
    console.log('axios headers fail:', err)
  }

  try{
    axios.interceptors.request.use(function (request) {
      //show loading 
      let cookiekey = getKey('cookiekey');//兼容方式[wx|gxb]获取cookiekey
      if (cookiekey) {
        startLoading()
      }
      return request;
    })
  } catch (err) {
    console.log('axios request fail:', err)
  }

  try{
    axios.interceptors.response.use(function (response) {
      //hide loading 
      if (response) {
        stopLoading()
      }
      return response;    // 每个请求所返回的数据
    }, function (error) {
      return Promise.reject(error)
    });
  } catch (err) {
    console.log('axios response fail:', err)
  }
  /**axios 拦截器 END */

  function startLoading() {
    //cover div
    var div = document.getElementById("wc_loading_div");
    if (div) {
      div.style.display = "block"
      return;
    }
    div = document.createElement('div');
    div.setAttribute("id", "wc_loading_div");
    div.style.position = "fixed";
    div.style.zIndex = "99999";
    div.style.left = "0";
    div.style.top = "0";
    div.style.width = "100%";
    div.style.height = "100vh";
    div.style.background = "rgba(0,0,0,.1)"

    //loading img
    var img = document.getElementById("wc_loading_img") || new Image();
    img.src = '../img/else/loading.svg?ver=1.0.0';
    img.id = 'wc_loading_img';
    img.style.position = "absolute";
    img.style.left = "50%";
    img.style.marginLeft = "-25px";
    img.style.top = "50%";
    img.style.marginTop = "-60px";
    img.style.width = "50px";
    img.style.height = "50px";    try {
      document.body.appendChild(div)
      div.appendChild(img)

      stopLoading(15000);//15s后自动隐藏
    } catch (err) {
      console.log('appendChild : loading=>',err)
    }
  }

  function stopLoading(ms = 100) {
    setTimeout(function () {
      document.getElementById("wc_loading_div").style.display = "none";
    }, ms)
  }

  /**获取URL某个参数 */
  function getUrlParams(param) {
    let reg = new RegExp("(^|&)" + param + "=([^&]*)(&|$)");
    let local = window.location;
    let r = local.search.substr(1).match(reg);
    if (r != null)
      return decodeURI(r[2]);//对encodeURI编码处理过的uri进行解码
    return null;
  }

  /**获取URL所有参数 */
  function getUrlAllParams(){
    var obj = {};
    //获取url的参数部分
    var params = window.location.search.substr(1);
    //[^&=]+ 表示不含&或=的连续字符,加上()就是提取对应字符串
    params.replace(/([^&=]+)=([^&=]*)/gi,function(rs,$1,$2){
      obj[$1] = $2;
    });
   
    return obj;
  }

  /** 修改URL中某个参数的值 */
  function setUrlParam(key,value) {
    var oUrl = window.location.href.toString();
    var rUrl=eval('/('+ key+'=)([^&]*)/gi');
    var nUrl = oUrl.replace(rUrl,key+'='+value); 
    return nUrl;
  }

  /**cookie相关 */

  /**读取cookies  */
  function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg))
      return unescape(arr[2]);
    else
      return null;
  }

  /**写cookies expires->days */
  function setCookie(name, value, expires = 3) {
    var exp = new Date();
    exp.setTime(exp.getTime() + expires * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
  }

  /**清除cookie */
  function delCookie(key) {
    var date = new Date();
    date.setTime(date.getTime() - 1);
    var delValue = getCookie(key);
    if (!!delValue) {
      document.cookie = key + '=' + delValue + ';expires=' + date.toGMTString();
    }
  }

  /**清除所有cookie */
  function clearAllCookie() {
    var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
    if (keys) {
      for (var i = keys.length; i--;)
        document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
    }
  }

  /**判断是否在微信内部运行 */
  function isWeixin() {
    const ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == 'micromessenger') {
      return true;
    } else {
      return false;
    }
  }
 

  /**获取localstorage */
  function getLocStore(key) {
    let currUnix = new Date().getTime();//now
    let expires = 6 * 24 * 3600 * 1000; //after six days
    let cookiestartunix = localStorage.getItem(key + "_expires")
    if (!cookiestartunix || cookiestartunix == 'undefined' || currUnix - cookiestartunix > expires) {
      localStorage.removeItem(key)
      localStorage.removeItem(key + "_expires")
      //过期或不存在
      return null;
    }
    let cookiekey = localStorage.getItem(key)
    if (cookiekey)
      return cookiekey
    else
      return null;
  }

  /**从cookie或localstorage中获取key值 */
  function getKey(key) {
    let fromCookie = getCookie(key);
    let fromStorage = getLocStore(key);
    return fromCookie || fromStorage
  }

  function unix2Date(format, startdate) {
    let date = startdate ? new Date(startdate * 1) : new Date();
    let y = date.getFullYear();
    let m = fixNum(date.getMonth() + 1);
    let d = fixNum(date.getDate());
    let hh = fixNum(date.getHours());
    let mm = fixNum(date.getMinutes());
    let ss = fixNum(date.getSeconds());
    let dt = format.replace("Y", y).replace("M", m).replace("D", d).replace("hh", hh).replace("mm", mm).replace("ss", ss);
    return dt;
  }

  function date2Unix(date) {
    let fixdate = date.indexOf('-') > 0 ? date.replace(/-/g, '/') : date;
    fixdate = new Date(fixdate)
    return fixdate.getTime();
  }

  function fixNum(num) {
    return num < 10 ? `0${num}` : num
  }

  /**
  * [getLastTime 根据传入日期返回距离当前的时间]
  * @param  {[type]} passedDT [过去的时间日期]
  * @param  {[type]} currDT   [当前或者传入的时间日期]
  * @return {[type]}          [相差的时间 'x天x月x日x时x分x秒']
  */
  function getLastTime(passedDT, currDT) {
    let date1, date2;
    if (passedDT) {
      passedDT = passedDT.indexOf('-') > 0 ? passedDT.replace(/-/g, '/') : passedDT;
      date1 = new Date(passedDT);
    } else {
      date1 = new Date();
    }
    if (currDT) {
      currDT = currDT.indexOf('-') > 0 ? currDT.replace(/-/g, '/') : currDT;
      date2 = new Date(currDT);
    } else {
      date2 = new Date();
    }
    var s1 = date1.getTime(), s2 = date2.getTime();
    var total = (s2 - s1) / 1000;

    var day = parseInt(total / (24 * 60 * 60));//计算整数天数
    var afterDay = total - day * 24 * 60 * 60;//取得算出天数后剩余的秒数
    var hour = parseInt(afterDay / (60 * 60));//计算整数小时数
    var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60;//取得算出小时数后剩余的秒数
    var min = parseInt(afterHour / 60);//计算整数分
    var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60;//取得算出分后剩余的秒数
    var sec = parseInt(afterMin);//计算整数秒
    var strTime = day + "天" + hour + "时" + min + "分" + sec + "秒";
    return strTime;
  }

  function urlAddParams(url, name, value) {
    let valKey = `${name}=${value}`
    let newUrl = url.indexOf('?') > 0 ? `${url}&${valKey}` : `${url}?${valKey}`
    return newUrl;
  } 
   
  
  /** 整数,浮点数验证 */
  function (val,isInt) isNum {
    var intgerReg = /^[1-9]+[0-9]*$/;
    var floatReg = /^[0-9]+.?[0-9]*$/;
    var regRes = isInt?intgerReg.test(val):floatReg.test(val);
    if (regRes) {
        return true;
    } else {
        return false;
    }
  }

  /** 手机号码用空格分割 */
  function telFormat(tel){ 
    tel = String(tel);
    //方式一
    return tel.replace(/(\d{3})(\d{4})(\d{4})/,function (rs,$1,$2,$3){
      return $1+" "+$2+" "+$3
    });
    //方式二
    return tel.replace(/(\d{3})(\d{4})(\d{4})/,"$1 $2 $3");
  }

  /** 手机号码隐藏中间部分 */
  function telSecrect(tel){  
    var sliceNumber = tel.slice(3,tel.length - 3);
    var newPhone = tel.replace(new RegExp(sliceNumber,'g'),'****');
    console.log(newPhone); //181****678
  }

  //获得字符串实际长度,中文2,英文1
  function getBytes (str) { 
    var realLength = 0, len = str.length, charCode = -1;
    for (var i = 0; i < len; i++) {
      charCode = str.charCodeAt(i);
      if (charCode >= 0 && charCode <= 128)
        realLength += 1;
      else
        realLength += 2;
    }
    return realLength;
  };  
 

  function Util() { }
  Util.prototype.getCookie = getCookie
  Util.prototype.setCookie = setCookie
  Util.prototype.isWeixin = isWeixin
  Util.prototype.getUrlParams = getUrlParams
  Util.prototype.getLocStore = getLocStore
  Util.prototype.getKey = getKey
  Util.prototype.unix2Date = unix2Date
  Util.prototype.getLastTime = getLastTime
  Util.prototype.fixNum = fixNum
  Util.prototype.urlAddParams = urlAddParams
  Util.prototype.delCookie = delCookie
  Util.prototype.clearAllCookie = clearAllCookie
  Util.prototype.hideStatisticsA = hideStatisticsA
  Util.prototype.setUrlParam = setUrlParam
  Util.prototype.isNum = isNum
  Util.prototype.startLoading = startLoading;//生成loading 
  Util.prototype.stopLoading = stopLoading;//结束loading    
  Util.prototype.getBytes = getBytes;//获取字符串(中/英文长度)  

  // axios.defaults.headers['cookiekey'] = 'cookiekeyvalue';  _global = (function () { return this || (0, eval)('this'); }());
  if (typeof module !== "undefined" && module.exports) {
    module.exports = Util;
  }
  if (typeof define === "function" && define.amd) {
    define(function () { return Util; });
  }
  !('Util' in _global) && (_global.Util = Util);
}());