269個JavaScript小函數( 二二二二二二二 )

91.返回當前url

export const currentURL = () => window.location.href;

92.獲取url參數(第一種)

/**

 * @param {*} name
 * @param {*} origin
   */
export function getUrlParam(name, origin = null) {
    let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    let r = null;
    if (origin == null) {
        r = window.location.search.substr(1).match(reg);
    } else {
        r = origin.substr(1).match(reg);
    }
    if (r != null) return decodeURIComponent(r[2]);
    return null;
}

93.獲取url參數(第二種)

 /**
     * @param {*} name
     * @param {*} origin
       */
       export function getUrlParams(name, origin = null) {
       let url = location.href;
       let temp1 = url.split('?');
       let pram = temp1[1];
       let keyValue = pram.split('&');
       let obj = {};
       for (let i = 0; i < keyValue.length; i++) {
           let item = keyValue[i].split('=');
       let key = item[0];
        let value = item[1];
        obj[key] = value;
    }
    return obj[name];

    }

94.修改url中的參數

 /**
     * @param { string } paramName
     * @param { string } replaceWith
       */
       export function replaceParamVal(paramName,replaceWith) {
   var oUrl = location.href.toString();
    var re=eval('/('+ paramName+'=)([^&]*)/gi');
    location.href = oUrl.replace(re,paramName+'='+replaceWith);
    return location.href;
    }

95.刪除url中指定的參數

 /**
     * @param { string } name
       */
       export function funcUrlDel(name){
       var loca =location;
       var baseUrl = loca.origin + loca.pathname + "?";
       var query = loca.search.substr(1);
       if (query.indexOf(name)>-1) {
           var obj = {};
           var arr = query.split("&");
           for (var i = 0; i < arr.length; i++) {
               arr[i] = arr[i].split("=");
               obj[arr[i][0]] = arr[i][1];
           }
           delete obj[name];
       var url = baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
        return url
    }
    }

96.獲取窗口可視範圍的高度

export function getClientHeight() {
    let clientHeight = 0;
    if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = (document.body.clientHeight < document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    else {
        clientHeight = (document.body.clientHeight > document.documentElement.clientHeight) ? document.body.clientHeight : document.documentElement.clientHeight;
    }
    return clientHeight;
}

97.獲取窗口可視範圍寬度

export function getPageViewWidth() {
    let d = document,
        a = d.compatMode == "BackCompat" ? d.body : d.documentElement;
    return a.clientWidth;
}

98.獲取窗口寬度

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

99.獲取窗口尺寸

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

100.獲取滾動條距頂部高度

export function getPageScrollTop() {
    let a = document;
    return a.documentElement.scrollTop || a.body.scrollTop;
}

101.獲取滾動條距左邊的高度

export function getPageScrollLeft() {
    let a = document;
    return a.documentElement.scrollLeft || a.body.scrollLeft;
}

102.開啓全屏

 /**
     * @param {*} element
       */
       export function launchFullscreen(element) {
       if (element.requestFullscreen) {
           element.requestFullscreen()
       } else if (element.mozRequestFullScreen) {
           element.mozRequestFullScreen()
       } else if (element.msRequestFullscreen) {
           element.msRequestFullscreen()
   } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullScreen()
    }
    }

103.關閉全屏

export function exitFullscreen() {
    if (document.exitFullscreen) {
        document.exitFullscreen()
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen()
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen()
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen()
    }
}

104.返回當前滾動條位置

export const getScrollPosition = (el = window) => ({
    x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
    y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

105.滾動到指定元素區域

export const smoothScroll = element =>{
    document.querySelector(element).scrollIntoView({
        behavior: 'smooth'
    });
};

106.平滑滾動到頁面頂部

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

107.http跳轉https

export const httpsRedirect = () => {
    if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};

108.檢查頁面底部是否可見

export const bottomVisible = () =>{
    return document.documentElement.clientHeight + window.scrollY >=
        (document.documentElement.scrollHeight || document.documentElement.clientHeight);
};

109.打開一個窗口

 /**
     * @param { string } url
     * @param { string } windowName
     * @param { number } width
     * @param { number } height
       */
       export function openWindow(url, windowName, width, height) {
       var x = parseInt(screen.width / 2.0) - width / 2.0;
       var y = parseInt(screen.height / 2.0) - height / 2.0;
       var isMSIE = navigator.appName == "Microsoft Internet Explorer";
       if (isMSIE) {
           var p = "resizable=1,location=no,scrollbars=no,width=";
           p = p + width;
           p = p + ",height=";
           p = p + height;
           p = p + ",left=";
           p = p + x;
           p = p + ",top=";
           p = p + y;
           window.open(url, windowName, p);
       } else {
           var win = window.open(
               url,
               "ZyiisPopup",
               "top=" +
               y +
               ",left=" +
               x +
               ",scrollbars=" +
               scrollbars +
               ",dialog=yes,modal=yes,width=" +
               width +
               ",height=" +
           height +
            ",resizable=no"
        );
        eval("try { win.resizeTo(width, height); } catch(e) { }");
        win.focus();
    }
    }

110.自適應頁面(rem)

 /**
     * @param { number } width
       */
       export function AutoResponse(width = 750) {
       const target = document.documentElement;
   target.clientWidth >= 600
        ? (target.style.fontSize = "80px")
        : (target.style.fontSize = target.clientWidth / width * 100 + "px");
    }

日期工具date工具函數

111.瀏覽器存儲相關storage工具函數

主要爲瀏覽器存儲方面的工具函數,大部分搬運自大神火狼1

112.localStorage 存貯

 /**
     * 目前對象值如果是函數 、RegExp等特殊對象存貯會被忽略
     * @param { String } key  屬性
 * @param { string } value 值
    */
    export const localStorageSet = (key, value) => {
    if (typeof (value) === 'object') value = JSON.stringify(value);
    localStorage.setItem(key, value)
    };

113.localStorage 獲取

 /**
     * @param {String} key  屬性
   */
    export const localStorageGet = (key) => {
    return localStorage.getItem(key)
    };

114.localStorage 移除

 /**
     * @param {String} key  屬性
   */
    export const localStorageRemove = (key) => {
    localStorage.removeItem(key)
    };

115.localStorage 存貯某一段時間失效

 /**
     * @param {String} key  屬性
     * @param {*} value 存貯值
     * @param { number } expire 過期時間,毫秒數
       */
       export const localStorageSetExpire = (key, value, expire) => {
   if (typeof (value) === 'object') value = JSON.stringify(value);
    localStorage.setItem(key, value);
    setTimeout(() => {
        localStorage.removeItem(key)
    }, expire)
    };

116.sessionStorage 存貯

 /**
     * @param {String} key  屬性
     * @param {*} value 值
   */
    export const sessionStorageSet = (key, value) => {
    if (typeof (value) === 'object') value = JSON.stringify(value);
    sessionStorage.setItem(key, value)
    };

117.sessionStorage 獲取

 /**
     * @param {String} key  屬性
   */
    export const sessionStorageGet = (key) => {
    return sessionStorage.getItem(key)
    };

118.sessionStorage 刪除

 /**
     * @param {String} key  屬性
   */
    export const sessionStorageRemove = (key) => {
    sessionStorage.removeItem(key)
    };

119.sessionStorage 存貯某一段時間失效

 /**
     * @param {String} key  屬性
     * @param {*} value 存貯值
     * @param {String} expire 過期時間,毫秒數
       */
       export const sessionStorageSetExpire = (key, value, expire) => {
   if (typeof (value) === 'object') value = JSON.stringify(value);
    sessionStorage.setItem(key, value);
    setTimeout(() => {
        sessionStorage.removeItem(key)
    }, expire)
    };

120.cookie 存貯

 /**
     * @param {String} key  屬性
     * @param {*} value  值
     * @param { String } expire  過期時間,單位天
   */
    export const cookieSet = (key, value, expire) => {
    const d = new Date();
    d.setDate(d.getDate() + expire);
    document.cookie = `${key}=${value};expires=${d.toUTCString()}`
    };

121.cookie 獲取

 /**
     * @param {String} key  屬性
       */
       export const cookieGet = (key) => {
       const cookieStr = unescape(document.cookie);
       const arr = cookieStr.split('; ');
       let cookieValue = '';
       for (let i = 0; i < arr.length; i++) {
           const temp = arr[i].split('=');
           if (temp[0] === key) {
               cookieValue = temp[1];
               break
       }
    }
    return cookieValue
    };

122.cookie 刪除

 /**
     * @param {String} key  屬性
   */
    export const cookieRemove = (key) => {
    document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
    };

123.更多的工具函數

這裏包含了平時可能常用的工具函數,包含數字,字符串,數組和對象等等操作。

124.金錢格式化,三位加逗號

 /**
  *  @param { number } num
     */
     export const formatMoney = num => num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

125.截取字符串並加身略號

export function subText(str, length) {
    if (str.length === 0) {
        return '';
    }
    if (str.length > length) {
        return str.substr(0, length) + "...";
    } else {
        return str;
    }
}

126.獲取文件base64編碼

 /**
     * @param file
     * @param format  指定文件格式
     * @param size  指定文件大小(字節)
     * @param formatMsg 格式錯誤提示
     * @param sizeMsg   大小超出限制提示
     * @returns {Promise<any>}
       */
       export function fileToBase64String(file, format = ['jpg', 'jpeg', 'png', 'gif'], size = 20 * 1024 * 1024, formatMsg = '文件格式不正確', sizeMsg = '文件大小超出限制') {
       return new Promise((resolve, reject) => {
           // 格式過濾
           let suffix = file.type.split('/')[1].toLowerCase();
           let inFormat = false;
           for (let i = 0; i < format.length; i++) {
               if (suffix === format[i]) {
                   inFormat = true;
                   break;
               }
           }
           if (!inFormat) {
               reject(formatMsg);
           }
           // 大小過濾
           if (file.size > size) {
               reject(sizeMsg);
           }
           // 轉base64字符串
       let fileReader = new FileReader();
        fileReader.readAsDataURL(file);
        fileReader.onload = () => {
            let res = fileReader.result;
            resolve({base64String: res, suffix: suffix});
            reject('異常文件,請重新選擇');
        }
    })
    }

127.B轉換到KB,MB,GB並保留兩位小數

 /**
     * @param { number } fileSize
       */
       export function formatFileSize(fileSize) {
       let temp;
       if (fileSize < 1024) {
           return fileSize + 'B';
       } else if (fileSize < (1024 * 1024)) {
           temp = fileSize / 1024;
           temp = temp.toFixed(2);
           return temp + 'KB';
       } else if (fileSize < (1024 * 1024 * 1024)) {
           temp = fileSize / (1024 * 1024);
           temp = temp.toFixed(2);
           return temp + 'MB';
       } else {
           temp = fileSize / (1024 * 1024 * 1024);
       temp = temp.toFixed(2);
        return temp + 'GB';
    }
    }

128.base64轉file

 /**
     *  @param { base64 } base64
     *  @param { string } filename 轉換後的文件名
        */
        export const base64ToFile = (base64, filename )=> {
        let arr = base64.split(',');
        let mime = arr[0].match(/:(.*?);/)[1];
        let suffix = mime.split('/')[1] ;// 圖片後綴
        let bstr = atob(arr[1]);
        let n = bstr.length;
        let u8arr = new Uint8Array(n);
    while (n--) {
         u8arr[n] = bstr.charCodeAt(n)
     }
     return new File([u8arr], `${filename}.${suffix}`, { type: mime })
     };

129.base64轉blob

 /**
     *  @param { base64 } base64
        */
        export const base64ToBlob = base64 => {
        let arr = base64.split(','),
            mime = arr[0].match(/:(.*?);/)[1],
            bstr = atob(arr[1]),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
     }
     return new Blob([u8arr], { type: mime });
     };

130.blob轉file

/**
    *  @param { blob } blob
    *  @param { string } fileName
       */
   export const blobToFile = (blob, fileName) => {
    blob.lastModifiedDate = new Date();
    blob.name = fileName;
    return blob;
    };
複製代碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章