12 個非常實用的 JavaScript 函數
本文收集了 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()
作者 | 代碼與野獸
https://juejin.cn/post/7127278574033174542
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/P5VtsWxJ2cNtHe-hEALPXg