1. 程式人生 > 其它 >常用的前端方法封裝2

常用的前端方法封裝2

輸入一個值,返回其資料型別

function type(para) {
    return Object.prototype.toString.call(para)
}

陣列去重

// 方法一
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') }

深拷貝 淺拷貝

//深克隆(深克隆不考慮函式)
function deepClone(obj, result) {
    
var result = result || {}; for (var prop in obj) { if (obj.hasOwnProperty(prop)) { if (typeof obj[prop] == 'object' && obj[prop] !== null) { // 引用值(obj/array)且不為null if (Object.prototype.toString.call(obj[prop]) == '[object Object]') { // 物件 result[prop] = {}; } else { // 陣列 result[prop] = []; } deepClone(obj[prop], result[prop]) } else { // 原始值或func result[prop] = obj[prop] } } } return result; } // 深淺克隆是針對引用值 function deepClone(target) { if (typeof (target) !== 'object') { return target; } var result; if (Object.prototype.toString.call(target) == '[object Array]') { // 陣列 result = [] } else { // 物件 result = {}; } for (var prop in target) { if (target.hasOwnProperty(prop)) { result[prop] = deepClone(target[prop]) } } return result; } // 無法複製函式 var o1 = jsON.parse(jsON.stringify(obj1));

找出字串中第一次只出現一次的字母

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;
    }
}

檢驗字串是否是迴文

function isPalina(str) {
    if (Object.prototype.toString.call(str) !== '[object String]') {
        return false;
    }
    var len = str.length;
    for (var i = 0; i < len / 2; i++) {
        if (str[i] != str[len - 1 - i]) {
            return false;
        }
    }
    return true;
}

檢驗字串是否是迴文

function isPalindrome(str) {
    str = str.replace(/\W/g, '').toLowerCase();
    console.log(str)
    return (str == str.split('').reverse().join(''))
}

相容 getElementsByClassName 方法

Element.prototype.getElementsByClassName = Document.prototype.getElementsByClassName = function (_className) {
    var allDomArray = document.getElementsByTagName('*');
    var lastDomArray = [];
    function trimSpace(strClass) {
        var reg = /\s+/g;
        return strClass.replace(reg, ' ').trim()
    }
    for (var i = 0; i < allDomArray.length; i++) {
        var classArray = trimSpace(allDomArray[i].className).split(' ');
        for (var j = 0; j < classArray.length; j++) {
            if (classArray[j] == _className) {
                lastDomArray.push(allDomArray[i]);
                break;
            }
        }
    }
    return lastDomArray;
}

運動函式

function animate(element, styleJson, callback) {
    clearInterval(element.timer);
    var speed,
        current;
    element.timer = setInterval(function () {
        var lock = true;
        for (var prop in styleJson) {
            if (prop == 'opacity') {
                current = parseFloat(window.getComputedStyle(element, null)[prop]) * 100;
            } else {
                current = parseInt(window.getComputedStyle(element, null)[prop]);
            }
            speed = (styleJson[prop] - current) / 7;
            // 計算動畫完成事件
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

            // 設定透明度
            if (prop == 'opacity') {
                element.style[prop] = (current + speed) / 100;
            } else if (typeof styleJson[prop] === "number") {
                element.style[prop] = current + speed + 'px';
            } else {
                element.style[prop] = styleJson[prop];
            }
            if (current != styleJson[prop]) {
                lock = false;
            }
        }
        if (lock) {
            clearInterval(element.timer);
            typeof callback == 'function' ? callback() : '';
        }
    }, 30)
}

示例1

// 點選按鈕檢視結果
function start() {
    let el = document.querySelector(".box");
    let styleJson = {
        width: 600,
        height: 300,
        backgroundColor: "red",
        opacity: 70
    }
    function calba() {
        console.log("執行完畢");
    }
    animate(el, styleJson, calba())
}

原生 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);
    }
}

驗證郵箱的正則表示式

function isAvailableEmail(sEmail) {
    var reg = /^([\w+\.])+@\w+([.]\w+)+$/
    return reg.test(sEmail)
}

防抖

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;
        }
    }
}