常用JS方法整理

冷星1024發表於2018-08-02

本篇目錄:

  • 1.擷取指定位元組數的字串
  • 2.判斷是否微信
  • 3.獲取時間格式的幾個舉例
  • 4.獲取字串位元組長度
  • 5.物件克隆、深拷貝
  • 6.組織結構程式碼證驗證
  • 7.身份證號驗證
  • 8.js正則為url新增http標識
  • 9.URL有效性校驗方法
  • 10.自定義jsonp方法
  • 11.cookie操作
  • 12.生成隨機字串 (可指定長度)
  • 13.瀏覽器判斷
  • 14.Rem移動端適配
  • 15.獲取url後引數
  • 16.動態載入JS
  • 17.生成隨機顏色值
  • 18.事件繫結與解綁
  • 19.移動端音訊播放
  • 20.移動端視訊適配

1.擷取指定位元組數的字串

/**
 * 擷取指定位元組的字串
 * @param str 要擷取的字元穿
 * @param len 要擷取的長度,根據位元組計算
 * @param suffix 擷取前len個後,其餘的字元的替換字元,一般用“…”
 * @returns {*}
 */
function cutString(str, len, suffix) {
  if (!str) return "";
  if (len <= 0) return "";
  if (!suffix) suffix = "";
  var templen = 0;
  for (var i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 255) {
      templen += 2;
    } else {
      templen++
    }
    if (templen == len) {
      return str.substring(0, i + 1) + suffix;
    } else if (templen > len) {
      return str.substring(0, i) + suffix;
    }
  }
  return str;
}
複製程式碼

2.判斷是否微信

/**
 * 判斷微信瀏覽器
 * @returns {Boolean}
 */
function isWeiXin() {
  var ua = window.navigator.userAgent.toLowerCase();
  if (ua.match(/MicroMessenger/i) == 'micromessenger') {
    return true;
  } else {
    return false;
  }
}
複製程式碼

3.獲取時間格式的幾個舉例

function getTimeFormat(time) {
  var date = new Date(parseInt(time) * 1000);
  var month, day, hour, min;
  parseInt(date.getMonth()) + 1 < 10 ? month = '0' + (parseInt(date.getMonth()) + 1) : month = parseInt(date.getMonth()) + 1;
  date.getDate() < 10 ? day = '0' + date.getDate() : day = date.getDate();
  date.getHours() < 10 ? hour = '0' + date.getHours() : hour = date.getHours();
  date.getMinutes() < 10 ? min = '0' + date.getMinutes() : min = date.getMinutes();
  return [month, day].join('-') + '  ' + hour + ':' + min
}

function getTimeFormatYMD(time) {
  var date = new Date(parseInt(time) * 1000);
  var year, month, day;
  year = date.getFullYear();
  parseInt(date.getMonth()) + 1 < 10 ? month = '0' + (parseInt(date.getMonth()) + 1) : month = parseInt(date.getMonth()) + 1;
  date.getDate() < 10 ? day = '0' + date.getDate() : day = date.getDate();
  return [year, month, day].join('-')
}

function getTimeFormatAll(time) {
  var date = new Date(parseInt(time) * 1000);
  var year, month, day, hour, min, second;
  year = date.getFullYear();
  parseInt(date.getMonth()) + 1 < 10 ? month = '0' + (parseInt(date.getMonth()) + 1) : month = parseInt(date.getMonth()) + 1;
  date.getDate() < 10 ? day = '0' + date.getDate() : day = date.getDate();
  date.getHours() < 10 ? hour = '0' + date.getHours() : hour = date.getHours();
  date.getMinutes() < 10 ? min = '0' + date.getMinutes() : min = date.getMinutes();
  date.getSeconds() < 10 ? second = '0' + date.getSeconds() : second = date.getSeconds();

  return [year, month, day].join('-') + '  ' + hour + ':' + min + ':' + second
}
複製程式碼

4.獲取字串位元組長度

/**
 * 獲取字串位元組長度
 * @param {String}
 * @returns {Boolean}
 */
function checkLength(v) {
  var realLength = 0;
  var len = v.length;
  for (var i = 0; i < len; i++) {
    var charCode = v.charCodeAt(i);
    if (charCode >= 0 && charCode <= 128) realLength += 1;
    else realLength += 2;
  }
  return realLength;
}
複製程式碼

5.物件克隆、深拷貝

/**
 * 物件克隆&深拷貝
 * @param obj
 * @returns {{}}
 */
function cloneObj(obj) {
  var newO = {};
  if (obj instanceof Array) {
    newO = [];
  }
  for (var key in obj) {
    var val = obj[key];
    newO[key] = typeof val === 'object' ? arguments.callee(val) : val;
  }
  return newO;
};
複製程式碼

克隆拷貝增強版

/**
 * 物件克隆&深拷貝
 * @param obj
 * @returns {{}}
 */
function clone(obj) {
  // Handle the 3 simple types, and null or undefined
  if (null == obj || "object" != typeof obj) return obj;
  // Handle Date
  if (obj instanceof Date) {
    var copy = new Date();
    copy.setTime(obj.getTime());
    return copy;
  }
  // Handle Array
  if (obj instanceof Array) {
    var copy = [];
    for (var i = 0,
    len = obj.length; i < len; ++i) {
      copy[i] = clone(obj[i]);
    }
    return copy;
  }
  // Handle Object
  if (obj instanceof Object) {
    var copy = {};
    for (attr in obj) {
      if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
    }
    return copy;
  }
  throw new Error("Unable to copy obj! Its type isn't supported.");
}
複製程式碼

測試用例:

var origin = {
  a: "text",
  b: null,
  c: undefined,
  e: {
    f: [1, 2]
  }
}
複製程式碼

6.組織結構程式碼證驗證

驗證規則:

組織機構程式碼是每一個機關、社會團體、企事業單位在全國範圍內唯一的、始終不變的法定程式碼標識。最新使用的組織機構程式碼在1997年頒佈實施,由8位數字(或大寫拉丁字母)本體程式碼和1位數字(或大寫拉丁字母)校驗碼組成。本體程式碼採用系列(即分割槽段)順序編碼方法。校驗碼按下列公式計算:8 C9 = 11 - MOD(∑Ci * Wi,11)… (2) i = 1其中:MOD——表示求餘函式;i——表示程式碼字元從左到右位置序號;Ci——表示第i位置上的程式碼字元的值,採用附錄A“程式碼字符集”所列字元;C9——表示校驗碼;Wi——表示第i位置上的加權因子,其數值如下表:i 1 2 3 4 5 6 7 8 Wi 3 7 9 10 5 8 4 2當MOD函式值為1(即C9 = 10)時,校驗碼用字母X表示。

驗證方法:

checkOrgCodeValid: function(el) {
  var txtval = el.value;
  var values = txtval.split("-");
  var ws = [3, 7, 9, 10, 5, 8, 4, 2];
  var str = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var reg = /^([0-9A-Z]){8}$/;
  if (!reg.test(values[0])) {
    return false
  }
  var sum = 0;
  for (var i = 0; i < 8; i++) {
    sum += str.indexOf(values[0].charAt(i)) * ws[i];
  }
  var C9 = 11 - (sum % 11);
  var YC9 = values[1] + '';
  if (C9 == 11) {
    C9 = '0';
  } else if (C9 == 10) {
    C9 = 'X';
  } else {
    C9 = C9 + '';
  }
  return YC9 == C9;
}
複製程式碼

7.身份證號驗證

/**
 * 驗證身份證號
 * @param el 號碼輸入input
 * @returns {boolean}
 */
function checkCardNo(el) {
  var txtval = el.value;
  var reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  return reg.test(txtval)
}
複製程式碼

8.js正則為url新增http標識

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">  
  <title></title>
  <script>
        var html = 'http:/ / www.google.com ';
        html += '\rwww.google.com ';
        html += '\rcode.google.com ';
        html += '\rhttp: //code.google.com/hosting/search?q=label%3aPython';
        var regex = /(https?:\/\/)?(\w+\.?)+(\/[a-zA-Z0-9\?%=_\-\+\/]+)?/gi;
        alert('before replace:');
        alert(html);
        html = html.replace(regex,
            function(match, capture) {
                if (capture) {
                    return match
                } else {
                    return 'http://' + match;
                }
            });
        alert('after replace:');
        alert(html); 
    </script>
</head>
<body>  
</body>
</html>

複製程式碼

9.URL有效性校驗方法

/**
 * URL有效性校驗
 * @param str_url
 * @returns {boolean}
 */
function isURL(str_url) { 
  // 驗證url
  var strRegex = "^((https|http|ftp|rtsp|mms)?://)" + "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" //           
  ftp的user@ + "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
  + "|" // 允許IP和DOMAIN(域名)
  + "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
  + "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二級域名
  + "[a-z]{2,6})" // first level domain- .com or .museum
  + "(:[0-9]{1,4})?" // 埠- :80
  + "((/?)|" // a slash isn't required if there is no file name
  + "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
  var re = new RegExp(strRegex);
  return re.test(str_url);
}
// 建議的正則
functionisURL(str) {
  return !! str.match(/(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/g);
}
複製程式碼

10.自定義jsonp方法

/**
 * 自定義封裝jsonp方法
 * @param options
 */
jsonp = function(options) {
  options = options || {};
  if (!options.url || !options.callback) {
    throw new Error("引數不合法");
  }
  //建立 script 標籤並加入到頁面中
  var callbackName = ('jsonp_' + Math.random()).replace(".", "");
  var oHead = document.getElementsByTagName('head')[0];
  options.data[options.callback] = callbackName;
  var params = formatParams(options.data);
  var oS = document.createElement('script');
  oHead.appendChild(oS);
  //建立jsonp回撥函式
  window[callbackName] = function(json) {
    oHead.removeChild(oS);
    clearTimeout(oS.timer);
    window[callbackName] = null;
    options.success && options.success(json);
  };
  //傳送請求
  oS.src = options.url + '?' + params;
  //超時處理
  if (options.time) {
    oS.timer = setTimeout(function() {
      window[callbackName] = null;
      oHead.removeChild(oS);
      options.fail && options.fail({
        message: "超時"
      });
    },
    time);
  }
};
/**
 * 格式化引數
 * @param data
 * @returns {string}
 */
formatParams = function(data) {
  var arr = [];
  for (var name in data) {
    arr.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
  }
  return arr.join('&');
}
複製程式碼

11.cookie操作

//寫cookies
setCookie = function(name, value, time) {
  var strsec = getsec(time);
  var exp = new Date();
  exp.setTime(exp.getTime() + strsec * 1);
  document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
//cookie操作輔助函式
getsec = function(str) {
  var str1 = str.substring(1, str.length) * 1;
  var str2 = str.substring(0, 1);
  if (str2 == "s") {
    return str1 * 1000;
  } else if (str2 == "h") {
    return str1 * 60 * 60 * 1000;
  } else if (str2 == "d") {
    return str1 * 24 * 60 * 60 * 1000;
  }
}
//讀取cookies
getCookie = function(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg)) return (arr[2]);
  else return null;
}

//刪除cookies
delCookie = function(name) {
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval = getCookie(name);
  if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
複製程式碼

12.生成隨機字串 (可指定長度)

/**
 * 生成隨機字串(可指定長度)
 * @param len
 * @returns {string}
 */
randomString = function(len) {
  len = len || 8;
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
  /****預設去掉了容易混淆的字元oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = '';
  for (var i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}
複製程式碼

13.瀏覽器判斷

function parseUA() {
  var u = navigator.userAgent;
  var u2 = navigator.userAgent.toLowerCase();
  return { //移動終端瀏覽器版本資訊
    trident: u.indexOf('Trident') > -1,
    //IE核心
    presto: u.indexOf('Presto') > -1,
    //opera核心
    webKit: u.indexOf('AppleWebKit') > -1,
    //蘋果、谷歌核心
    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1,
    //火狐核心
    mobile: !!u.match(/AppleWebKit.*Mobile.*/),
    //是否為移動終端
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
    //ios終端
    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
    //android終端或uc瀏覽器
    iPhone: u.indexOf('iPhone') > -1,
    //是否為iPhone或者QQHD瀏覽器
    iPad: u.indexOf('iPad') > -1,
    //是否iPad
    webApp: u.indexOf('Safari') == -1,
    //是否web應該程式,沒有頭部與底部
    iosv: u.substr(u.indexOf('iPhone OS') + 9, 3),
    weixin: u2.match(/MicroMessenger/i) == "micromessenger",
    ali: u.indexOf('AliApp') > -1,
  };
}
var ua = parseUA();
if (!ua.mobile) {
  location.href = './pc.html';
}

複製程式碼

14.Rem移動端適配

var rem = {
  baseRem: 40,
  // 基準字號,按照iphone6應該為20,此處擴大2倍,便於計算
  baseWidth: 750,
  // 基準尺寸寬,此處是按照ihpone6的尺寸
  rootEle: document.getElementsByTagName("html")[0],
  initHandle: function() {
    this.setRemHandle();
    this.resizeHandle();
  },
  setRemHandle: function() {
    var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
    this.rootEle.style.fontSize = clientWidth * this.baseRem / this.baseWidth + "px";
  },
  resizeHandle: function() {
    var that = this;
    window.addEventListener("resize",
    function() {
      setTimeout(function() {
        that.setRemHandle();
      },
      300);
    });
  }
};
rem.initHandle();
複製程式碼

15.獲取url後引數

function GetRequest() {
  var url = location.search; //獲取url中"?"符後的字串
  var theRequest = new Object();
  if (url.indexOf("?") != -1) {
    var str = url.substr(1);
    strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = (strs[i].split("=")[1]);
    }
  }
  return theRequest;
}
複製程式碼

16.動態載入JS

function loadScript(url, callback) {
  var script = document.createElement("script");
  script.type = "text/";
  if (typeof(callback) != "undefined") {
    if (script.readyState) {
      script.onreadystatechange = function() {
        if (script.readyState == "loaded" || script.readyState == "complete") {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else {
      script.onload = function() {
        callback();
      };
    }
  }
  script.src = url;
  document.body.appendChild(script);
}
複製程式碼

17.生成隨機顏色值

function getRandomColor () {
  const rgb = []
  for (let i = 0 ; i < 3; ++i){
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}
複製程式碼

18.事件繫結與解綁

ElementClass.prototype.on = function (name, callback) {
    this.callbacks[name] = this.callbacks[name] || []
    this.callbacks[name].push(callback)
}

ElementClass.prototype.off = function (name, callback) {
    var callbacks = this.callbacks[name]
    if (callbacks && callbacks instanceof Array) {
        var index = callbacks.indexOf(callback)
        if (index !== -1) callbacks.splice(index, 1)
    }
}

ElementClass.prototype.trigger = function (name, params) {
    var callbacks = this.callbacks[name]
    if (callbacks && callbacks instanceof Array) {
        callbacks.forEach((cb) => {
            cb(params)
        })
    }
}
複製程式碼

19.移動端音訊播放

/**
  * 移動端H5播放音樂處理,相容微信端
  * @param el 音樂Audio元素
  */
function playMusic(el) {
    var b = document.getElementById(el);

    var c = function c() {
        b.play();
        document.removeEventListener("touchstart", c, true);
    };

    b.play();
    document.addEventListener("WeixinJSBridgeReady", function () {
        c();
    }, false);
    document.addEventListener("YixinJSBridgeReady", function () {
        c();
    }, false);
    document.addEventListener("touchstart", c, true);
}
複製程式碼

20.移動端視訊適配

<video class="video1" webkit-playsinline="true" x-webkit-airplay="true" playsinline="true" x5-video-player-type="h5" x5-video-player-fullscreen="true"  preload="auto" poster="poster圖片地址" src="視訊地址"></video>
複製程式碼

相關文章