js常备方法

67 阅读1分钟

收集开发中高频次使用的js方法,持续更新中...

全屏显示元素

const goToFullScreen = (element) => {  
    element = element || document.body; 
    if (element.requestFullscreen) {   
        element.requestFullscreen();  
    } else if (element.mozRequestFullScreen) { 
        element.mozRequestFullScreen();  
    } else if (element.msRequestFullscreen) {  
        element.msRequestFullscreen(); 
    } else if (element.webkitRequestFullscreen) {
        element.webkitRequestFullScreen(); 
    }
};

退出全屏显示

const goExitFullscreen = () => {  
    if (document.exitFullscreen) {
        document.exitFullscreen();
    } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
        document.webkitExitFullscreen();
    }
};

获取数据类型

const getType = (value) => {
    const match = Object.prototype.toString.call(value).match(/ (\w+)]/)
    return match[1].toLocaleLowerCase()
}

getType() // undefined
getType({}}) // object
getType([]) // array
getType(1) // numberget
Type('fatfish') // string
getType(true) // boolean
getType(/fatfish/) // regexp

停止冒泡事件

一种适用于所有平台的防止事件冒泡的方法。

const stopPropagation = (event) => {
    event = event || window.event;
    if (event.stopPropagation) {
        event.stopPropagation();
    } else {
        event.cancelBubble = true;
    }
};

深拷贝一个深度嵌套对象

const deepCopy = (obj, hash = new WeakMap()) => {
    if (obj instanceof Date) {
        return new Date(obj);
    }
    if (obj instanceof RegExp) {
        return new RegExp(obj);
    }
    if (hash.has(obj)) {
        return hash.get(obj);
    }
    let allDesc = Object.getOwnPropertyDescriptors(obj);
    let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);
    hash.set(obj, cloneObj);
    for (let key of Reflect.ownKeys(obj)) {
        if (obj[key] && typeof obj[key] === "object") {
            cloneObj[key] = deepCopy(obj[key], hash);
        } else {
            cloneObj[key] = obj[key];
        }
    }
    return cloneObj;
};

确定设备类型

const isMobile = () => {
return !!navigator.userAgent.match(
/(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i);
}

判断设备是安卓还是IOS

const isAndroid = () => {
    return /android/i.test(navigator.userAgent.toLowerCase());
};

const isIOS = () => {
    let reg = /iPhone|iPad|iPod|iOS|Macintosh/i;
    return reg.test(navigator.userAgent.toLowerCase());
};

获取浏览器类型及其版本

const getExplorerInfo = () => {
    let t = navigator.userAgent.toLowerCase();
    return 0 <= t.indexOf("msie")
    ? {
        //ie < 11
        type: "IE",
        version: Number(t.match(/msie ([\d]+)/)[1]),
    }
    : !!t.match(/trident\/.+?rv:(([\d.]+))/)
    ? {
        // ie 11
        type: "IE",
        version: 11,
    }
    : 0 <= t.indexOf("edge")
    ? {
        type: "Edge",
        version: Number(t.match(/edge\/([\d]+)/)[1]),
    }
    : 0 <= t.indexOf("firefox")
    ? {
        type: "Firefox",
        version: Number(t.match(/firefox\/([\d]+)/)[1]),
    }
    : 0 <= t.indexOf("chrome")
    ? {
        type: "Chrome",
        version: Number(t.match(/chrome\/([\d]+)/)[1]),
    }
    : 0 <= t.indexOf("opera")
    ? {
        type: "Opera",
        version: Number(t.match(/opera.([\d]+)/)[1]),
    }
    : 0 <= t.indexOf("Safari")
    ? {
        type: "Safari",
        version: Number(t.match(/version\/([\d]+)/)[1]),
    }
    : {
        type: t,
        version: -1,
    };
};

生成随机字符串

const randomString = (len) => {
    let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
    let strLen = chars.length;
    let randomStr = "";
    for (let i = 0; i < len; i++) {
        randomStr += chars.charAt(Math.floor(Math.random() * strLen));
    }
    return randomStr;
};

randomString(10) // pfkMfjEJ6x
randomString(20) // ce6tEx1km4idRNMtym2S

生成指定范围内的随机数

const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

格式化货币

const formatMoney = (money) => {
    return money.toLocaleString()
}

formatMoney(123456789) // '123,456,789'
formatMoney(123456789.123) // '123,456,789.123'
formatMoney(123) // '123'

手机号脱敏

export const hideMobile = (mobile) => {
  return mobile.replace(/^(\d{3})\d{4}(\d{4})$/"$1****$2")
}

滚动到页面顶部

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

滚动到元素位置

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

uuid

export const uuid = () => {
  const temp_url = URL.createObjectURL(new Blob())
  const uuid = temp_url.toString()
  URL.revokeObjectURL(temp_url) //释放这个url
  return uuid.substring(uuid.lastIndexOf('/') + 1)
}

判断一个参数是不是函数

function isFunction(v){  
   return ['[object Function]''[object GeneratorFunction]''[object AsyncFunction]''[object Promise]'].includes(Object.prototype.toString.call(v));  
}

获取随机颜色

function getRandomColor(){  
    return `#${Math.floor(Math.random() * 0xffffff) .toString(16)}`;  
}