美文网首页
常用的前端JavaScript方法封装

常用的前端JavaScript方法封装

作者: 臭臭的胡子先生 | 来源:发表于2023-04-03 15:39 被阅读0次
    获取url中的参
    function getWindonHref() {
        var sHref = window.location.href;
        var args = sHref.split('?');
        if (args[0] === sHref) {
            return '';
        }
        var hrefarr = args[1].split('#')[0].split('&');
        var obj = {};
        for (var i = 0; i < hrefarr.length; i++) {
            hrefarr[i] = hrefarr[i].split('=');
            obj[hrefarr[i][0]] = hrefarr[i][1];
        }
        return obj;
    }
    
    //方法二
    const getUrlParam = function(name) { // 获取url参数
      let reg = new RegExp('(^|&?)' + name + '=([^&]*)(&|$)', 'i')
      let r = window.location.href.substr(1).match(reg)
      if (r != null) {
        return decodeURI(r[2])
      }
      return undefined
    }
    //方法三
    function getUrlParam(sUrl, sKey) {
        var result = {};
        sUrl.replace(/(\w+)=(\w+)(?=[&|#])/g, function (ele, key, val) {
            if (!result[key]) {
                result[key] = val;
            } else {
                var temp = result[key];
                result[key] = [].concat(temp, val);
            }
        })
        if (!sKey) {
            return result;
        } else {
            return result[sKey] || '';
        }
    }
    
    输入一个值,返回其数据类型
    function type(para) {
        return Object.prototype.toString.call(para)
    }
    
    返回当前的时间(年月日时分秒)
    function getDateTime() {
        var date = new Date(),
            year = date.getFullYear(),
            month = date.getMonth() + 1,
            day = date.getDate(),
            hour = date.getHours() + 1,
            minute = date.getMinutes(),
            second = date.getSeconds();
            month = checkTime(month);
            day = checkTime(day);
            hour = checkTime(hour);
            minute = checkTime(minute);
            second = checkTime(second);
         function checkTime(i) {
            if (i < 10) {
                    i = "0" + i;
           }
          return i;
        }
        return "" + year + "年" + month + "月" + day + "日" + hour + "时" + minute + "分" + second + "秒"
    }
    
    数组去重
    function unique1(arr) {
        return [...new Set(arr)]
    }
    
    function unique2(arr) {
        var obj = {};
        return arr.filter(ele => {
            if (!obj[ele]) {
                obj[ele] = true;
                return true;
            }
        })
    }
    
    function unique3(arr) {
        var result = [];
        arr.forEach(ele => {
            if (result.indexOf(ele) == -1) {
                result.push(ele)
            }
        })
        return result;
    }
    
    字符串去重
    String.prototype.unique = function () {
        var obj = {},
            str = '',
            len = this.length;
        for (var i = 0; i < len; i++) {
            if (!obj[this[i]]) {
                str += this[i];
                obj[this[i]] = true;
            }
        }
        return str;
    }
    
    ###### //去除连续的字符串 
    function uniq(str) {
        return str.replace(/(\w)\1+/g, '$1')
    }
    
    reverse底层原理和扩展
    // 改变原数组
    Array.prototype.myReverse = function () {
        var len = this.length;
        for (var i = 0; i < len; i++) {
            var temp = this[i];
            this[i] = this[len - 1 - i];
            this[len - 1 - i] = temp;
        }
        return this;
    }
    
    圣杯模式的继承
    function inherit(Target, Origin) {
        function F() {};
        F.prototype = Origin.prototype;
        Target.prototype = new F();
        Target.prototype.constructor = Target;
        // 最终的原型指向
        Target.prop.uber = Origin.prototype;
    }
    
    找出字符串中第一次只出现一次的字母
    String.prototype.firstAppear = function () {
        var obj = {},
            len = this.length;
        for (var i = 0; i < len; i++) {
            if (obj[this[i]]) {
                obj[this[i]]++;
            } else {
                obj[this[i]] = 1;
            }
        }
        for (var prop in obj) {
           if (obj[prop] == 1) {
             return prop;
           }
        }
    }
    
    找元素的第n级父元素
    function parents(ele, n) {
        while (ele && n) {
            ele = ele.parentElement ? ele.parentElement : ele.parentNode;
            n--;
        }
        return ele;
    }
    
    返回元素的第n个兄弟节点
    function retSibling(e, n) {
        while (e && n) {
            if (n > 0) {
                if (e.nextElementSibling) {
                    e = e.nextElementSibling;
                } else {
                    for (e = e.nextSibling; e && e.nodeType !== 1; e = e.nextSibling);
                }
                n--;
            } else {
                if (e.previousElementSibling) {
                    e = e.previousElementSibling;
                } else {
                    for (e = e.previousElementSibling; e && e.nodeType !== 1; e = e.previousElementSibling);
                }
                n++;
            }
        }
        return e;
    }
    
    判断元素有没有子元素
    function hasChildren(e) {
        var children = e.childNodes,
            len = children.length;
        for (var i = 0; i < len; i++) {
            if (children[i].nodeType === 1) {
                return true;
            }
        }
        return false;
    }
    
    我一个元素插入到另一个元素的后面
    Element.prototype.insertAfter = function (target, elen) {
        var nextElen = elen.nextElenmentSibling;
        if (nextElen == null) {
            this.appendChild(target);
        } else {
            this.insertBefore(target, nextElen);
        }
    }
    
    获得滚动条的滚动距离
    function getScrollOffset() {
        if (window.pageXOffset) {
            return {
                x: window.pageXOffset,
                y: window.pageYOffset
            }
        } else {
            return {
                x: document.body.scrollLeft + document.documentElement.scrollLeft,
                y: document.body.scrollTop + document.documentElement.scrollTop
            }
        }
    }
    
    获得视口的尺寸
    function getViewportOffset() {
        if (window.innerWidth) {
            return {
                w: window.innerWidth,
                h: window.innerHeight
            }
        } else {
            // ie8及其以下
            if (document.compatMode === "BackCompat") {
                // 怪异模式
                return {
                    w: document.body.clientWidth,
                    h: document.body.clientHeight
                }
            } else {
                // 标准模式
                return {
                    w: document.documentElement.clientWidth,
                    h: document.documentElement.clientHeight
                }
            }
        }
    }
    
    获取任一元素的任意属性
    function getStyle(elem, prop) {
        return window.getComputedStyle ? window.getComputedStyle(elem, null)[prop] : elem.currentStyle[prop]
    }
    
    绑定事件的兼容代码
    function addEvent(elem, type, handle) {
        if (elem.addEventListener) { //非ie和非ie9
            elem.addEventListener(type, handle, false);
        } else if (elem.attachEvent) { //ie6到ie8
            elem.attachEvent('on' + type, function () {
                handle.call(elem);
            })
        } else {
            elem['on' + type] = handle;
        }
    }
    
    解绑事件
    function removeEvent(elem, type, handle) {
        if (elem.removeEventListener) { //非ie和非ie9
            elem.removeEventListener(type, handle, false);
        } else if (elem.detachEvent) { //ie6到ie8
            elem.detachEvent('on' + type, handle);
        } else {
            elem['on' + type] = null;
        }
    }
    
    取消冒泡的兼容代码
    function stopBubble(e) {
        if (e && e.stopPropagation) {
            e.stopPropagation();
        } else {
            window.event.cancelBubble = true;
        }
    }
    
    数组reduce方法
    Array.prototype.myReduce = function (func, initialValue) {
        var len = this.length,
            nextValue,
            i;
        if (!initialValue) {
            // 没有传第二个参数
            nextValue = this[0];
            i = 1;
        } else {
            // 传了第二个参数
            nextValue = initialValue;
            i = 0;
        }
        for (; i < len; i++) {
            nextValue = func(nextValue, this[i], i, this);
        }
        return nextValue;
    }
    
    数组排序
    // 快排 [left] + min + [right]
    function quickArr(arr) {
        if (arr.length <= 1) {
            return arr;
        }
        var left = [],
            right = [];
        var pIndex = Math.floor(arr.length / 2);
        var p = arr.splice(pIndex, 1)[0];
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] <= p) {
                left.push(arr[i]);
            } else {
                right.push(arr[i]);
            }
        }
        // 递归
        return quickArr(left).concat([p], quickArr(right));
    }
    
    // 冒泡
    function bubbleSort(arr) {
        for (var i = 0; i < arr.length - 1; i++) {
            for (var j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    var temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
        return arr;
    }
    
    function bubbleSort(arr) {
        var len = arr.length;
        for (var i = 0; i < len - 1; i++) {
            for (var j = 0; j < len - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    var temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }
    
    遍历Dom树
    function traverse(element, callback) {
        callback(element);
        var list = element.children;
        for (var i = 0; i < list.length; i++) {
            traverse(list[i], callback);
        }
    }
    
    原生js封装ajax
    function ajax(method, url, callback, data, flag) {
        var xhr;
        flag = flag || true;
        method = method.toUpperCase();
        if (window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject('Microsoft.XMLHttp');
        }
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                console.log(2)
                callback(xhr.responseText);
            }
        }
    
        if (method == 'GET') {
            var date = new Date(),
            timer = date.getTime();
            xhr.open('GET', url + '?' + data + '&timer' + timer, flag);
            xhr.send()
            } else if (method == 'POST') {
            xhr.open('POST', url, flag);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.send(data);
        }
    }
    
    cookie管理
    var cookie = {
        set: function (name, value, time) {
            document.cookie = name + '=' + value + '; max-age=' + time;
            return this;
        },
        remove: function (name) {
            return this.setCookie(name, '', -1);
        },
        get: function (name, callback) {
            var allCookieArr = document.cookie.split('; ');
            for (var i = 0; i < allCookieArr.length; i++) {
                var itemCookieArr = allCookieArr[i].split('=');
                if (itemCookieArr[0] === name) {
                    return itemCookieArr[1]
                }
            }
            return undefined;
        }
    }
    
    防抖
    function debounce(handle, delay) {
        var timer = null;
        return function () {
            var _self = this,
                _args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                handle.apply(_self, _args)
            }, delay)
        }
    }
    
    节流
    function throttle(handler, wait) {
        var lastTime = 0;
        return function (e) {
            var nowTime = new Date().getTime();
            if (nowTime - lastTime > wait) {
                handler.apply(this, arguments);
                lastTime = nowTime;
            }
        }
    }
    
    常用正则验证
    const checkStr = function(str, type) { // 常用正则验证,注意type大小写
      switch (type) {
        case 'phone': // 手机号码
          return /^1[3|4|5|6|7|8|9][0-9]{9}$/.test(str)
        case 'tel': // 座机
          return /^(0\d{2,3}-\d{7,8})(-\d{1,4})?$/.test(str)
        case 'card': // 身份证
          return /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(str)
        case 'pwd': // 密码以字母开头,长度在6~18之间,只能包含字母、数字和下划线
          return /^[a-zA-Z]\w{5,17}$/.test(str)
        case 'postal': // 邮政编码
          return /[1-9]\d{5}(?!\d)/.test(str)
        case 'QQ': // QQ号
          return /^[1-9][0-9]{4,9}$/.test(str)
        case 'email': // 邮箱
          return /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/.test(str)
        case 'money': // 金额(小数点2位)
          return /^\d*(?:\.\d{0,2})?$/.test(str)
        case 'URL': // 网址
          return /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?/.test(str)
        case 'IP': // IP
          return /((?:(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))/.test(str)
        case 'date': // 日期时间
          return /^(\d{4})\-(\d{2})\-(\d{2}) (\d{2})(?:\:\d{2}|:(\d{2}):(\d{2}))$/.test(str) ||
            /^(\d{4})\-(\d{2})\-(\d{2})$/.test(str)
        case 'number': // 数字
          return /^[0-9]$/.test(str)
        case 'english': // 英文
          return /^[a-zA-Z]+$/.test(str)
        case 'chinese': // 中文
          return /^[\u4E00-\u9FA5]+$/.test(str)
        case 'lower': // 小写
          return /^[a-z]+$/.test(str)
        case 'upper': // 大写
          return /^[A-Z]+$/.test(str)
        case 'HTML': // HTML标记
          return /<("[^"]*"|'[^']*'|[^'">])*>/.test(str)
        default:
          return true
      }
    }
    
    图片地址转base64
    const getBase64 = function(img) { //传入图片路径,返回base64,使用getBase64(url).then(function(base64){},function(err){}); 
      let getBase64Image = function(img, width, height) { //width、height调用时传入具体像素值,控制大小,不传则默认图像大小
        let canvas = document.createElement("canvas");
        canvas.width = width ? width : img.width;
        canvas.height = height ? height : img.height;
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        let dataURL = canvas.toDataURL();
        return dataURL;
      }
      let image = new Image();
      image.crossOrigin = '';
      image.src = img;
      let deferred = $.Deferred();
      if (img) {
        image.onload = function() {
          deferred.resolve(getBase64Image(image));
        }
        return deferred.promise();
      }
    }
    
    base64图片下载功能
    const downloadFile = function(base64, fileName) { //base64图片下载功能
      let base64ToBlob = function(code) {
        let parts = code.split(';base64,');
        let contentType = parts[0].split(':')[1];
        let raw = window.atob(parts[1]);
        let rawLength = raw.length;
        let uInt8Array = new Uint8Array(rawLength);
        for (let i = 0; i < rawLength; ++i) {
          uInt8Array[i] = raw.charCodeAt(i);
        }
        return new Blob([uInt8Array], {
          type: contentType
        });
      };
      let aLink = document.createElement('a');
      let blob = base64ToBlob(base64); //new Blob([content]);
      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true); //initEvent不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      aLink.click();
    }
    

    相关文章

      网友评论

          本文标题:常用的前端JavaScript方法封装

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