JS兼容及常用工具代碼封裝

本文目錄:

  • 1.格式化日期時(shí)間函數(shù)(formatDate(dt))
  • 2.獲取當(dāng)前瀏覽器的類型(getBrowserType)
  • 3.獲取頁面向上或者向左卷曲出去的距離(getPageScroll)
  • 4.限制字符顯示字?jǐn)?shù)(cutLongString(string, number))
  • 5.ajax原生代碼封裝(ajax(url,type,async,timeout,data,success,error))
  • 6.比值函數(shù)(compareUp,compareDown,compareObjArr(prop))
  • 7.獲取地址欄參數(shù)(getUrlParamString(name))
  • 8.移動端適配方案,rem快速布局
  • 9.移動端PC端頁面動態(tài)跳轉(zhuǎn)解決方案
    1. 取min-max之間的隨機(jī)數(shù)(getRandom(min, max),getRandomPlus(min, max))
  • 11.獲取傳入?yún)?shù)的數(shù)據(jù)類型(getParamType(val))
  • 12.深拷貝遞歸函數(shù)(deepCopy(obj))
  • 13.讓頁面滾動到頂部(scrollToPageTop)
  • 14.判斷指定el是否在視口范圍內(nèi)(ifElementIsVisibleInViewport(el))
  • 15.劫持粘貼板(copyTextToClipboard(value))
  • 16.將阿拉伯?dāng)?shù)字翻譯成中文的大寫數(shù)字(numberToChinese(num))
  • 17.檢測密碼強(qiáng)度(checkPwd(str))
  • 18.轉(zhuǎn)碼和解碼(htmlDecodeByRegExp(str),htmlEncodeByRegExp(str))
  • 19.最近n天(getLatestDay)
  • 20.禁止蒙層底部頁面跟隨滾動(bodyScrollToggle)
  • 21.防抖(debounceFunc(handle, delay))
  • 22.節(jié)流(throttleFunc(handler, wait))

1.格式化日期時(shí)間函數(shù)

參數(shù):只有一個(gè)必傳參數(shù)
默認(rèn)參數(shù)是當(dāng)前的時(shí)間對象
參數(shù)支持傳入時(shí)間對象,或者距 1970 年 1 月 1 日之間的毫秒數(shù)
返回值是一個(gè)對象{}

function formatDate(dt) {
  if (typeof dt === "object") {
  } else if (typeof dt === "number") {
    dt = new Date(dt);
  } else {
    dt = new Date();
  }
  var str = ""; //存儲時(shí)間的字符串
  //獲取年
  var year = dt.getFullYear();
  //獲取月
  var month = dt.getMonth() + 1;
  //獲取日
  var day = dt.getDate();
  //獲取小時(shí)
  var hour = dt.getHours();
  //獲取分鐘
  var min = dt.getMinutes();
  //獲取秒
  var sec = dt.getSeconds();
  month = month < 10 ? "0" + month : month;
  day = day < 10 ? "0" + day : day;
  hour = hour < 10 ? "0" + hour : hour;
  min = min < 10 ? "0" + min : min;
  sec = sec < 10 ? "0" + sec : sec;
  str =
    year + "年" + month + "月" + day + "日 " + hour + ":" + min + ":" + sec;
  return {
    year,
    month,
    day,
    hour,
    min,
    sec,
    str,
  };
}

2.獲取當(dāng)前瀏覽器的類型

在處理一些兼容性問題的形式可以根據(jù)下面的判定進(jìn)行處理。

function getBrowserType() {
    var broType = ''
    var browserName = navigator.userAgent.toLowerCase()
    if (/msie/i.test(browserName) && !/opera/.test(browserName)) {
        broType = "IE"
    } else if (/firefox/i.test(browserName)) {
        broType = "Firefox"
    } else if (/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)) {
        broType = "Chrome"
    } else if (/opera/i.test(browserName)) {
        broType = "Opera"
    } else if (/webkit/i.test(browserName) && !(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName))) {
        broType = "Safari"
    } else {
        broType = "Unknown"
    }
    return broType
}

3.獲取頁面向上或者向左卷曲出去的距離

下面封裝的函數(shù)可以實(shí)現(xiàn)最大兼容性的獲取到想要的值,返回值是一個(gè)對象,top屬性對應(yīng)的向上卷曲出去的距離值,left屬性對應(yīng)的向左卷曲出去的距離值。

function getPageScroll() {
    return {
        top: window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0,
        left: window.pageXOffset || document.body.scrollLeft || document.documentElement.scrollLeft || 0
    }
}

4.限制字符顯示字?jǐn)?shù)

方法需要傳兩個(gè)參數(shù),第一個(gè)參數(shù)是需要傳入的字符串,第二個(gè)參數(shù)是需要保留的字符串字?jǐn)?shù)

function cutLongString(string, number) {
    let newString = ''
    if (string.length > number) {
        return newString = string.substring(0, number) + '...'
    } else {
        return newString
    }
}

5.ajax原生代碼封裝

調(diào)用時(shí)的參數(shù)

ajax({
    url: "", //請求地址
    type: 'GET', //請求方式
    async: true,//同步異步設(shè)置
    timeout: 6000,//超時(shí)設(shè)置
    data: {
        name: '',
        age: '',
        email: ''
    }, //請求參數(shù)
    success: function(response, xml) {
        console.log(response); //   此處執(zhí)行請求成功后的回調(diào)
    },
    error: function(status) {
        console.log('狀態(tài)碼為' + status); // 此處為請求失敗后的回調(diào)
    }
})

代碼封裝

const ajax = function (options) {
    options = options || {};
    options.type = (options.type || "GET").toUpperCase();
    options.dataType = options.dataType || 'json';
    options.async = options.async || true;
    options.timeout = options.timeout || 5000;//超時(shí)處理,默認(rèn)5s
    var params = getParams(options.data);
    var timeoutFlag = null;
    var xhr;
    var that = this;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    } else {
        xhr = new ActiveXObject('Microsoft.XMLHTTP')
    }
    xhr.onreadystatechange = function () {
        if (options.dataType === 'json') {
            if (xhr.readyState == 4) {
                window.clearTimeout(that.timeoutFlag);
                var status = xhr.status;
                if (status >= 200 && status < 300) {
                    // 如果需要像 html 表單那樣 POST 數(shù)據(jù),請使用 setRequestHeader() 來添加 http 頭。
                    options.success && options.success(xhr.responseText, xhr.responseXML);
                } else {
                    options.error && options.error(status);
                }
            }
        } else {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
                window.clearTimeout(that.timeoutFlag);
                var oScript = document.createElement('script');
                document.body.appendChild(oScript);
                var callbackname = 'ajaxCallBack'
                oScript.src = options.url + "?" + params + '&callback=' + callbackname;
                window['ajaxCallBack'] = function (data) {
                    options.success(data);
                    document.body.removeChild(oScript);
                };
            }
        }
    };
    if (options.type == 'GET') {
        xhr.open("GET", options.url + '?' + params, options.async);
        xhr.send(null)
    } else if (options.type == 'POST') {
        xhr.open('POST', options.url, options.async);
        if (options.contentType == "undefined" || options.contentType == null) {
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(params);
        } else {
            xhr.setRequestHeader('Content-Type', options.contentType);
            xhr.send(JSON.stringify(options.data));
        }
    }
    this.timeoutFlag = window.setTimeout(function () {//計(jì)時(shí)器,超時(shí)后處理
        window.clearTimeout(that.timeoutFlag);
        //options.error("timeout");
        xhr.abort();
    }.bind(this), options.timeout);
}
function getParams(data) {
    var arr = [];
    for (var param in data) {
        arr.push(encodeURIComponent(param) + '=' + encodeURIComponent(data[param]));
    }
    return arr.join('&');
}

6.比值函數(shù)

普通比值函數(shù):直接把變量放入sort方法中即可

const compareUp = function (a, b) {//升序比值函數(shù)
    if (a < b) {
        return -1;
    } else if (a > b) {
        return 1;
    } else {
        return 0;
    }
}
const compareDown = function (a, b) {//降序比值函數(shù)
    if (a < b) {
        return 1;
    } else if (a > b) {
        return -1;
    } else {
        return 0;
    }
}

排序?qū)ο髷?shù)組的比值函數(shù):參數(shù)傳入要進(jìn)行排序的屬性名

const compareObjArr = function (prop) {
    return function (obj1, obj2) {
        var val1 = obj1[prop];
        var val2 = obj2[prop];
        if (!isNaN(Number(val1)) && !isNaN(Number(val2))) {
            val1 = Number(val1);
            val2 = Number(val2);
        }
        if (val1 < val2) {
            return -1;
        } else if (val1 > val2) {
            return 1;
        } else {
            return 0;
        }
    }
}

7.獲取地址欄參數(shù)

參數(shù)傳入什么,返回的就是地址欄上對應(yīng)的參數(shù)值

const getUrlParamString = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 構(gòu)造一個(gè)含有目標(biāo)參數(shù)的正則表達(dá)式對象
    var r = window.location.search.substr(1).match(reg);  // 匹配目標(biāo)參數(shù)
    if (r != null) return unescape(r[2]); return null; // 返回參數(shù)值
}

8.移動端適配方案,rem快速布局

PC端使用請將此代碼注釋掉
750px圖,圖片尺寸/100=rem尺寸
iphone調(diào)試開發(fā),屏幕尺寸/100*2=rem尺寸

(function () {
    var width = document.documentElement.clientWidth;
    var html = document.querySelector("html");
    html.style.fontSize = width / 7.5 + "px";
})();

9.移動端PC端頁面動態(tài)跳轉(zhuǎn)解決方案

將此JS代碼放到跳板頁面的頭部

function IsPC() {
    var userAgentInfo = navigator.userAgent;
    var Agents = ["Android", "iPhone",
        "SymbianOS", "Windows Phone",
        "iPad", "iPod"];
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            flag = false;
            break;
        }
    }
    return flag;
}
IsPC();
if (!IsPC()) {
    //跳到移動端
    window.location.href = '';
} else {
    //跳到PC端
    window.location.href = '';
}

10. 取min-max之間的隨機(jī)數(shù)

函數(shù)始終返回介于 min(包括)和 max(不包括)之間的隨機(jī)數(shù)
函數(shù)始終返回介于 min(包括)和 max(不包括)之間的隨機(jī)整數(shù)

const getRandom = function (min, max) {
    return Math.floor(Math.random() * (max - min) ) + min;
}

這個(gè) JavaScript 函數(shù)始終返回介于 min 和 max(都包括)之間的隨機(jī)整數(shù):

const getRandomPlus = function (min, max) {
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

11.獲取傳入?yún)?shù)的數(shù)據(jù)類型

const getParamType = function (val) {
    var s = Object.prototype.toString.call(val)
    var shorts = s.slice(8)
    return shorts.replace(shorts.slice(-1), '').toLowerCase()
}

12.深拷貝遞歸函數(shù)

根據(jù)傳遞進(jìn)來的參數(shù),返回值是一個(gè)深拷貝出來的新數(shù)據(jù)

const deepCopy = function (obj) {
    var newobj = obj.constructor === Array ? [] : {};
    if (typeof obj !== 'object') {
        return;
    }
    for (var i in obj) {
        newobj[i] = typeof obj[i] === 'object' ?
        deepCopy(obj[i]) : obj[i];
    }
    return newobj
}

13.讓頁面滾動到頂部

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

14.判斷指定el是否在視口范圍內(nèi)

需要指定的el全部都在視口范圍內(nèi)才會返回true,只要有任何一部分不在視口范圍都會返回false

const ifElementIsVisibleInViewport = (el, partiallyVisible = false) => {
    const {
        top,
        left,
        bottom,
        right
    } = el.getBoundingClientRect();
    const {
        innerHeight,
        innerWidth
    } = window;
    return partiallyVisible ?
        ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) :
        top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
}

15.劫持粘貼板

比如想要將類名為demo的文本內(nèi)容復(fù)制到粘貼板,先獲取到內(nèi)容let demo = document.querySelector(".demo"),然后調(diào)用工具函數(shù)copyTextToClipboard(demo.innerText)

const copyTextToClipboard = (value) => {
    var textArea = document.createElement("textarea");
    textArea.style.background = 'transparent';
    textArea.value = value;
    document.body.appendChild(textArea);
    textArea.select();
    try {
        var successful = document.execCommand('copy');
    } catch (err) {
        console.log('Oops, unable to copy');
    }
    document.body.removeChild(textArea);
}

16.將阿拉伯?dāng)?shù)字翻譯成中文的大寫數(shù)字

const numberToChinese = (num) => {
    var AA = new Array("零", "一", "二", "三", "四", "五", "六", "七", "八", "九", "十");
    var BB = new Array("", "十", "百", "仟", "萬", "億", "點(diǎn)", "");
    var a = ("" + num).replace(/(^0*)/g, "").split("."),
        k = 0,
        re = "";
    for (var i = a[0].length - 1; i >= 0; i--) {
        switch (k) {
            case 0:
                re = BB[7] + re;
                break;
            case 4:
                if (!new RegExp("0{4}//d{" + (a[0].length - i - 1) + "}$")
                    .test(a[0]))
                    re = BB[4] + re;
                break;
            case 8:
                re = BB[5] + re;
                BB[7] = BB[5];
                k = 0;
                break;
        }
        if (k % 4 == 2 && a[0].charAt(i + 2) != 0 && a[0].charAt(i + 1) == 0)
            re = AA[0] + re;
        if (a[0].charAt(i) != 0)
            re = AA[a[0].charAt(i)] + BB[k % 4] + re;
        k++;
    }
    if (a.length > 1) // 加上小數(shù)部分(如果有小數(shù)部分)
    {
        re += BB[6];
        for (var i = 0; i < a[1].length; i++)
            re += AA[a[1].charAt(i)];
    }
    if (re == '一十')
        re = "十";
    if (re.match(/^一/) && re.length == 3)
        re = re.replace("一", "");
    return re;
}

17.檢測密碼強(qiáng)度

當(dāng)返回值為0時(shí),提示密碼長度不得少于6位數(shù)
數(shù)字,小寫字母,大寫字母,.-_三種特殊符號,每多一種,安全級別加1,最高級別4

const checkPwd = (str) => {
    let Lv = 0;
    if (str.length < 6) {
        return Lv
    }
    if (/[0-9]/.test(str)) {
        Lv++
    }
    if (/[a-z]/.test(str)) {
        Lv++
    }
    if (/[A-Z]/.test(str)) {
        Lv++
    }
    if (/[\.|-|_]/.test(str)) {
        Lv++
    }
    return Lv;
}

18.轉(zhuǎn)碼和解碼

const htmlDecodeByRegExp = function (str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/&#39;/g, "'");
    s = s.replace(/&quot;/g, '"');
    return s;
}
const htmlEncodeByRegExp = function (str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&/g, "&amp;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "&#39;");
    s = s.replace(/\"/g, "&quot;");
    return s;
}

19.最近n天

兩個(gè)參數(shù),第1個(gè)參數(shù)是數(shù)字類型,代表想要的是最近幾天
第二個(gè)參數(shù)是字符串類型,asc代表升序,desc代表降序
兩個(gè)參數(shù)都是選填,不傳的話默認(rèn)是返回最近7天的升序

const getLatestDay = function (n=7, sort) {
    sort = sort || 'asc'
    if (sort === 'asc') {
        return [...new Array(n)].map((j, i) => new Date(Date.now() - i * 8.64e7).toLocaleDateString()).reverse()
    } else if (sort === 'desc') {
        return [...new Array(n)].map((j, i) => new Date(Date.now() - i * 8.64e7).toLocaleDateString())
    }
}

20.禁止蒙層底部頁面跟隨滾動

既然我們要阻止頁面滾動,那么何不將其固定在視窗(即position: fixed),這樣它就無法滾動了,當(dāng)蒙層關(guān)閉時(shí)再釋放。
當(dāng)然還有一些細(xì)節(jié)要考慮,將頁面固定視窗后,內(nèi)容會回頭最頂端,這里我們需要記錄一下,同步top值。

let topPosition = 0

const bodyScrollToggle = function (isFixed) {
let bodyEl = document.body
  if (isFixed) {
    topPosition = window.scrollY
    bodyEl.style.position = 'fixed'
    bodyEl.style.top = -topPosition + 'px'
  } else {
    bodyEl.style.position = ''
    bodyEl.style.top = ''
    window.scrollTo(0, topPosition) // 回到原先的top
  }
}

21.防抖

const debounceFunc = function (handle, delay) {
    var timer = null;
    return function () {
        var _self = this,
            _args = arguments;
        clearTimeout(timer);
        timer = setTimeout(function () {
            handle.apply(_self, _args)
        }, delay)
    }
}

22.節(jié)流

const throttleFunc = function (handler, wait) {
    var lastTime = 0;
    return function (e) {
        var nowTime = new Date().getTime();
        if (nowTime - lastTime > wait) {
            handler.apply(this, arguments);
            lastTime = nowTime;
        }
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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