你用的上的JS函数

142 阅读1分钟

随机生成颜色

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

数组排序

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("放假啦")

检测暗色主题

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

滚动到顶部

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

滚动到底部

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

检测元素是否在屏幕中

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

检测设备

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

深拷贝对象

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

是否为字符串

export const isString = (e) =>{ return Object.prototype.toString.call(e).slice(8,-1) === 'String' }