常用js函式封裝

章超勝的部落格發表於2018-02-28
//===============================Array==================================//

/** 
 * 陣列去重
 */
Array.prototype.Unique = function () {
    return [...new Set(this)];
}
/** 
 * 陣列刪除某一項
 * @param {String} let 要刪除那一項的值
 */
Array.prototype.DeleteByVal = function (val) {
    return this.filter(function (item) {
        return item !== val;
    })
}
//===============================Date==================================//

/** 
 * 日期格式化
 * @param {String} format default 'yyyy-MM-dd hh:mm:ss'  'yyyy-MM-dd'
 */
Date.prototype.DateFormat = function (format = 'yyyy-MM-dd hh:mm:ss') {
    let o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (let k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return format;
}

/** 
 * 獲取距離今天的N天的日期  N可正可負
 * @param {Number} interval default 0  -n 表示前幾天  n表示後幾天
 */
function getIntervalDate(interval = 0) {
    interval = Number(interval)
    let currentDate = new Date();
    currentDate.setDate(currentDate.getDate() + interval);
    let year = currentDate.getFullYear();
    let month = (currentDate.getMonth() + 1) < 10 ? "0" + (currentDate.getMonth() + 1) : (currentDate.getMonth() + 1);
    let day = currentDate.getDate() < 10 ? "0" + currentDate.getDate() : currentDate.getDate();
    return year + "-" + month + "-" + day;
}

/** 
 * 時間戳格式化為日期格式
 * @param {Number} timestamp 時間戳
 * @param {String} format default 'yyyy-MM-dd hh:mm:ss'  'yyyy-MM-dd' 
 */
function timestampToDate(timestamp, format = 'yyyy-MM-dd hh:mm:ss') {
    return new Date(parseInt(timestamp) * 1000).DateFormat(format);
}

//===============================Object==================================//
/** 
 * 克隆物件
 * @param {Object} source 
 */
function Clone(source) {
    return JSON.parse(JSON.stringify(source))
}




/**
 * 設定樣式
 * @param {HTMLElement} elem 需要設定的節點
 * @param {Object} prop      CSS屬性,鍵值物件
 */
function setStyle(elem, prop) {
    if (!elem) {
        return false
    };
    for (let i in prop) {
        elem.style[i] = prop[i];
    }
};
/**
 * 獲取節點css屬性
 * @param  {HTMLElement} elem 需要獲取的節點
 * @param  {String} name      css屬性
 * @return {String}           屬性值
 */
function getStyle(elem, name) { // 獲取CSS屬性函式
    if (elem.style[name] != '') return elem.style[name];
    if (!!window.ActiveXObject) return elem.currentStyle[name];
    return document.defaultView.getComputedStyle(elem, "").getPropertyValue(name.replace(/([A-Z])/g, "-$1").toLowerCase());
}

/**
 * 獲取滑鼠游標相對於整個頁面的位置
 * @return {String} 值
 */
function getX(e) {
    e = e || window.event;
    let _left = document.documentElement.scrollLeft || document.body.scrollLeft;
    return e.pageX || e.clientX + _left;
}

function getY(e) {
    e = e || window.event;
    let _top = document.documentElement.scrollTop || document.body.scrollTop;
    return e.pageY || e.clientY + _top;
}

/**
 * 獲取class命名的節點
 * @param  {String} className CSS命名
 * @param  {String} tag       標籤名稱/去全部標籤時用 *
 * @param  {HTMLElement} parent    查詢的範圍,通常為包含內容的父節點
 * @return {Array}           返回篩選節點的陣列集合
 */
function getElementsByClassName(className, tag, parent) {
    parent = parent || document;
    tag = tag || "*";
    let allTags = (tag === "*" && parent.all) ? parent.all : parent.getElementsByTagName(tag);
    let classElems = [];
    className = className.replace(/\-/g, "\\-");
    let regex = new RegExp("(^|\\s)" + className + "(\\s|$)");
    for (let i = 0; i < allTags.length; i++) {
        elem = allTags[i];
        if (regex.test(elem.className)) {
            classElems.push(elem);
        };
    };
    return classElems;
};

/**
 * 為目標元素新增事件監聽器
 * @method on||addEvent
 * @static
 * @param {HTMLElement} elem 目標元素
 * @param {String} type 事件名稱 如:click|mouseover
 * @param {Function} listener 需要新增的監聽器
 * @return 返回操作的元素節點
 */
function on(elem, type, listener) {
    type = type.replace(/^on/i, '').toLowerCase();
    let realListener = listener;
    // 事件監聽器掛載
    if (elem.addEventListener) {
        elem.addEventListener(type, realListener, false);
    } else if (elem.attachEvent) {
        elem.attachEvent('on' + type, realListener);
    }
    return elem;
};

let EventHandle = {
    addEvent:function(ele,type,handle){
        if(ele.addEventListener){
            ele.addEventListener(type,handle,false);
        }else if(ele.attachEvent){
            ele.attachEvent("on"+type,handle);
        }else{
            ele["on"+type] = handle;
        }
    },
    deleteEvent:function(ele,type,handle){
        if(ele.removeEventListener){
            ele.removeEventListener(type,handle,false);
        }else if(ele.detachEvent){
            ele.detachEvent("on"+type,handle);
        }else{
            ele["on"+type] = null;
        }
    }
}


/**
 * 千分位顯示 常用於價格
 * @param {Number} num
 */
function toThousands(num) {
    return parseFloat(num).toFixed(2).replace(/(\d{1,3})(?=(\d{3})+(?:\.))/g, "$1,");
}
console.log(toThousands(252121321.25))


/**
 * 動態載入 CSS 樣式檔案
 */
function LoadStyle(url) {
    try {
        document.createStyleSheet(url);
    } catch (e) {
        let cssLink = document.createElement('link');
        cssLink.rel = 'stylesheet';
        cssLink.type = 'text/css';
        cssLink.href = url;
        let head = document.getElementsByTagName('head')[0];
        head.appendChild(cssLink);
    }
}


/**
 * 返回瀏覽器版本
 */

function getExplorerInfo() {
    let explorer = window.navigator.userAgent.toLowerCase();
    // ie
    if (explorer.indexOf("msie") >= 0) {
        let ver = explorer.match(/msie ([\d.]+)/)[1];
        return {
            type: "IE",
            version: ver
        };
    }
    // firefox
    else if (explorer.indexOf("firefox") >= 0) {
        let ver = explorer.match(/firefox\/([\d.]+)/)[1];
        return {
            type: "Firefox",
            version: ver
        };
    }
    // Chrome
    else if (explorer.indexOf("chrome") >= 0) {
        let ver = explorer.match(/chrome\/([\d.]+)/)[1];
        return {
            type: "Chrome",
            version: ver
        };
    }
    // Opera
    else if (explorer.indexOf("opera") >= 0) {
        let ver = explorer.match(/opera.([\d.]+)/)[1];
        return {
            type: "Opera",
            version: ver
        };
    }
    // Safari
    else if (explorer.indexOf("Safari") >= 0) {
        let ver = explorer.match(/version\/([\d.]+)/)[1];
        return {
            type: "Safari",
            version: ver
        };
    }
}


/**
 * 判斷是否移動裝置
 */
function isMobile() {
    if (typeof this._isMobile === 'boolean') {
        return this._isMobile;
    }
    let screenWidth = this.getScreenWidth();
    let fixViewPortsExperiment = rendererModel.runningExperiments.FixViewport ||
        rendererModel.runningExperiments.fixviewport;
    let fixViewPortsExperimentRunning = fixViewPortsExperiment &&
        (fixViewPortsExperiment.toLowerCase() === "new");
    if (!fixViewPortsExperiment) {
        if (!this.isAppleMobileDevice()) {
            screenWidth = screenWidth / window.devicePixelRatio;
        }
    }
    let isMobileScreenSize = screenWidth < 600;
    let isMobileUserAgent = false;
    this._isMobile = isMobileScreenSize && this.isTouchScreen();
    return this._isMobile;
}



/**
 * 判斷是否移動裝置訪問
 */
function isMobileUserAgent() {
    return (/iphone|ipod|android.*mobile|windows.*phone|blackberry.*mobile/i
        .test(window.navigator.userAgent.toLowerCase()));
}


/**
 * 判斷是否蘋果移動裝置訪問
 */
function isAppleMobileDevice() {
    return (/iphone|ipod|ipad|Macintosh/i.test(navigator.userAgent
        .toLowerCase()));
}

/**
 * 判斷是否安卓移動裝置訪問
 */
function isAndroidMobileDevice() {
    return (/android/i.test(navigator.userAgent.toLowerCase()));
}

/**
 * 判斷是否Touch螢幕
 */
function isTouchScreen() {
    return (('ontouchstart' in window) || window.DocumentTouch &&
        document instanceof DocumentTouch);
}

/**
 * 判斷是否在安卓上的谷歌瀏覽器
 */
function isNewChromeOnAndroid() {
    if (isAndroidMobileDevice()) {
        let userAgent = navigator.userAgent.toLowerCase();
        if ((/chrome/i.test(userAgent))) {
            let parts = userAgent.split('chrome/');

            let fullVersionString = parts[1].split(" ")[0];
            let versionString = fullVersionString.split('.')[0];
            let version = parseInt(versionString);

            if (version >= 27) {
                return true;
            }
        }
    }
    return false;
}


/**
 * 獲取頁面高度
 */
function getPageHeight() {
    let g = document,
        a = g.body,
        f = g.documentElement,
        d = g.compatMode == "BackCompat" ?
        a :
        g.documentElement;
    return Math.max(f.scrollHeight, a.scrollHeight, d.clientHeight);
}

/**
 * 獲取頁面scrollLeft
 */
function getPageScrollLeft() {
    return document.documentElement.scrollLeft || document.body.scrollLeft;
}


/**
 * 獲取頁面寬度
 */
function getPageWidth() {
    let g = document,
        a = g.body,
        f = g.documentElement,
        d = g.compatMode == "BackCompat" ?
        a :
        g.documentElement;
    return Math.max(f.scrollWidth, a.scrollWidth, d.clientWidth);
}

/**
 * 獲取頁面scrollTop
 */
function getPageScrollTop() {
    return document.documentElement.scrollTop || document.body.scrollTop;
}

/**
 * 獲取頁面可視高度
 */
function getPageViewHeight() {
    let d = document,
        a = d.compatMode == "BackCompat" ?
        d.body :
        d.documentElement;
    return a.clientHeight;
}


function MouseWheelHandle (obj,handle){
    let info = navigator.userAgent;
    let down = null;
    if(info.indexOf("Firefox") !=-1){
        obj.addEventListener("DOMMouseScroll",function(event){
            let ev = event ||window.event;
                if(ev.detail>0){
                    down = true;
                }else{
                    down = false;            
                }
                handle(down,ev);
                handle.apply(obj,[down,ev]);
        },false);
    }else{
        obj.onmousewheel = function(event){
            let ev = event || window.event;
            if(ev.wheelDelta >0){
                down =false;
            }else{
                down = true;
            }
            handle(down,ev);
            handle.apply(obj,[down,ev]);
            handle.call(obj,down,ev);
        }
    }
}

相關文章