龙空技术网

10 个非常实用的 JavaScript 函数

滴水bule 46

前言:

此时你们对“js的random函数”大体比较着重,我们都需要分析一些“js的random函数”的相关内容。那么小编在网上收集了一些对于“js的random函数””的相关内容,希望我们能喜欢,大家一起来了解一下吧!

一、生成随机颜色

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("Hello World!")
四、检测暗色主题
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) {      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);
八、检测设备UA
const detectDeviceType = () =>  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(    navigator.userAgent  ) ? "Mobile" : "Desktop";console.log(detectDeviceType());
九、从 URL 中获取参数
const getParamByUrl = (key) => {  const url = new URL(location.href)  return url.searchParams.get(key)}
十、深拷贝对象
const deepCopy = obj => JSON.parse(JSON.stringify(obj))

标签: #js的random函数