JS实用技巧


滚动到页面顶部

  • 使用 window.scrollTo() 平滑滚动到页面顶部
    const scrollToTop = () => {
      window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
    };

滚动到页面底部

  • 知道页面的高度,也可以平滑滚动到页面底部
    const scrollToBottom = () => {
      window.scrollTo({
        top: document.documentElement.offsetHeight,
        left: 0,
        behavior: "smooth",
      });
    };

滚动元素到可见区域

  • 使用 scrollIntoView 将元素滚动到可见区域
    const smoothScroll = (element) => {
      element.scrollIntoView({
        behavior: "smooth",
      });
    };

全屏显示元素

  • 在浏览器中全屏打开某个元素,常用于视频全屏播放
    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) // number
    getType('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;
};

确定设备类型

  • 通过识别浏览器的 userAgent 来确定设备类型
    const isMobile = () => {
      return !!navigator.userAgent.match(
        /(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
      );
    };

判断设备是安卓还是IOS

  • 除了区分是移动端还是PC端,很多时候我们还需要区分当前设备是Android还是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,
          };
    };

设置cookies

const setCookie = (key, value, expire) => {
  const d = new Date();
  d.setDate(d.getDate() + expire);
  document.cookie = `${key}=${value};expires=${d.toUTCString()}`;
};
const getCookie = (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;
};

删除cookies

const delCookie = (key) => {
  document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`;
};

生成随机字符串

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 fistLetterUpper = (str) => {
  return str.charAt(0).toUpperCase() + str.slice(1);
};

fistLetterUpper('fatfish') // Fatfish

生成指定范围内的随机数

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

randomNum(1, 10) // 6
randomNum(10, 20) // 11

打乱数组的顺序

const shuffleArray = (array) => {
  return array.sort(() => 0.5 - Math.random())
}

let arr = [ 1, -1, 10, 5 ]

shuffleArray(arr) // [5, -1, 10, 1]
shuffleArray(arr) // [1, 10, -1, 5]

从数组中获取随机值

const getRandomValue = array => array[Math.floor(Math.random() * array.length)]; 
const prizes = [  '$100', '🍫', '🍔' ]

getRandomValue(prizes) // 🍫
getRandomValue(prizes) // 🍔
getRandomValue(prizes) // 🍫

格式化货币

  • 格式化货币的方式有很多,比如这两种方式
    // 第一种方法
    const formatMoney = (money) => {
      return money.replace(new RegExp(`(?!^)(?=(\\d{3})+${money.includes('.') ? '\\.' : '$'})`, 'g'), ',')  
    }
    formatMoney('123456789') // '123,456,789'
    formatMoney('123456789.123') // '123,456,789.123'
    formatMoney('123') // '123'
    
    // 第二种方式
    // 正则表达式让我们很头疼,不是吗?所以我们需要找到一种更简单的方式来格式化货币。
    const formatMoney = (money) => {
      return money.toLocaleString()
    }
    formatMoney(123456789) // '123,456,789'
    formatMoney(123456789.123) // '123,456,789.123'
    formatMoney(123) // '123'

简易评星判断

// 变量rate取值为:1-5,1代表一星、5代表五星
"★★★★★☆☆☆☆☆".slice(5 - rate, 10 - rate); 

Tips

原文链接


文章作者: Damao
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Damao !
  目录