携手创造,一起成长!这是我参加「日新计划 8 月更文挑战」的第 4 天,点击查看活动详情

本文收集了 12 个在日常开发中十分常用的函数,有些或许很复杂,有些或许很简略,但我信任或多或少会对咱们都会有所协助。

生成随机色彩

你的网站是否需要生成随机色彩?下面一行代码就能够完成。

const generateRandomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16)}`
console.log(generateRandomHexColor())

数组重排序

对数组的元素进行从头排序是一项十分重要的技巧,可是原生 Array 中并没有这项功用。

const shuffle = (arr) => arr.sort(() => Math.random() - 0.5)
const arr = [1, 2, 3, 4, 5]
console.log(shuffle(arr))

复制到剪切板

复制到剪切板是一项十分实用且能够提高用户便利性的功用。

const copyToClipboard = (text) => navigator.clipboard && navigator.clipboard.writeText && navigator.clipboard.writeText(text)
copyToClipboard("Hello World!")

检测暗色主题

暗色主题日益普及,很多用的都会在设备中启用案模式,咱们将应用程序切换到暗色主题能够提高用户体会度。

const isDarkMode = () => window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
console.log(isDarkMode())

翻滚到顶部

将元素翻滚到顶部最简略的办法是运用 scrollIntoView。设置 block 为 start 能够翻滚到顶部;设置 behavior 为 smooth 能够敞开平滑翻滚。

const scrollToTop = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "start" });

翻滚到底部

与翻滚到顶部相同,翻滚到底部只需要设置 block 为 end 即可。

const scrollToBottom = (element) =>
  element.scrollIntoView({ behavior: "smooth", block: "end" });

检测元素是否在屏幕中

查看元素是否在窗口中最好的办法是运用 IntersectionObserver。

const callback = (entries) => {
  entries.forEach((entry) => {
    if (entry.isIntersecting) {
      // `entry.target` is the dom element
      console.log(`${entry.target.id} is visible`);
    }
  });
};
const options = {
  threshold: 1.0,
};
const observer = new IntersectionObserver(callback, options);
const btn = document.getElementById("btn");
const bottomBtn = document.getElementById("bottom-btn");
observer.observe(btn);
observer.observe(bottomBtn);

检测设备

运用 navigator.userAgent 来检测网站运行在哪种平台设备上。

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  ) ? "Mobile" : "Desktop";
console.log(detectDeviceType());

隐藏元素

咱们能够将元素的 style.visibility 设置为 hidden,隐藏元素的可见性,但元素的空间依然会被占用。如果设置元素的 style.display 为 none,会将元素从渲染流中删除。

const hideElement = (el, removeFromFlow = false) => {
  removeFromFlow ? (el.style.display = 'none')
  : (el.style.visibility = 'hidden')
}

从 URL 中获取参数

JavaScript 中有一个 URL 目标,通过它能够十分便利的获取 URL 中的参数。

const getParamByUrl = (key) => {
  const url = new URL(location.href)
  return url.searchParams.get(key)
}

深复制目标

深复制目标十分简略,先将目标转换为字符串,再转换成目标即可。

const deepCopy = obj => JSON.parse(JSON.stringify(obj))

除了利用 JSON 的 API,还有更新的深复制目标的 structuredClone API,但并不是在所有的浏览器中都支持。

structuredClone(obj)

等候函数

JavaScript 供给了 setTimeout 函数,可是它并不回来 Promise 目标,所以咱们没办法运用 async 效果在这个函数上,可是咱们能够封装等候函数。

const wait = (ms) => new Promise((resolve)=> setTimeout(resolve, ms))
const asyncFn = async () => {
  await wait(1000)
  console.log('等候异步函数执行结束')
}
asyncFn()

感谢你的阅览,如果本文对你有所协助,不妨点个赞吧。