你需要了解的12个常用JavaScript函数帮助。生成随机颜色您的网站是否需要生成随机颜色?以下代码行将执行此操作。constgenerateRandomHexColor=()=>`#${Math.floor(Math.random()*0xffffff).toString(16)}`console.log(generateRandomHexColor())数组重新排序重新排序数组的元素是一个非常重要的技巧,但原生数组中没有这样的功能。constshuffle=(arr)=>arr.sort(()=>Math.random()-0.5)constarr=[1,2,3,4,5]console.log(shuffle(arr))复制到剪辑从剪贴板复制到剪贴板是一个非常有用的功能,可以提高用户的便利性。constcopyToClipboard=(text)=>navigator.clipboard&&navigator.clipboard.writeText&&navigator.clipboard.writeText(text)copyToClipboard("HelloWorld!")深色主题检测深色主题越来越流行,很多用户将在设备中启用案例模式,我们将应用程序切换为深色主题以改善用户体验。constisDarkMode=()=>window.matchMedia&&window.matchMedia("(prefers-color-scheme:dark)").matches;console.log(isDarkMode())滚动到顶部将元素滚动到顶部的最简单方法是使用scrollIntoView。设置块开始滚动到顶部;将行为设置为平滑以启用平滑滚动。constscrollToTop=(element)=>element.scrollIntoView({behavior:"smooth",block:"start"});滚动到底部和滚动到顶部是一样的,滚动到底部只需要设置blocktoend即可。constscrollToBottom=(element)=>element.scrollIntoView({行为:“平滑”,块:“结束”});检测元素是否在屏幕上检查元素是否在窗口上的最佳方法是使用IntersectionObserver。constcallback=(entries)=>{entries.forEach((entry)=>{if(entry.isIntersecting){//`entry.target`是dom元素console.log(`${entry.target.id}可见`);}});};constoptions={threshold:1.0,};constobserver=newIntersectionObserver(callback,options);constbtn=document.getElementById("btn");constbottomBtn=document.getElementById("bottom-btn");observer.observe(btn);observer.observe(bottomBtn);检测设备使用navigator.userAgent检测网站运行在哪个平台设备上。constdetectDeviceType=()=>/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent)?“移动设备”:“桌面设备”;console.log(detectDeviceType());隐藏的元素我们可以将元素的style.visibility设置为hidden来隐藏元素的可见性,但是元素的空间还是会被占用。将元素的style.display设置为none会将元素从渲染流中移除。consthideElement=(el,removeFromFlow=false)=>{removeFromFlow?(el.style.display='none'):(el.style.visibility='hidden')}从URL获取参数JavaScript有一个URL对象,通过它可以很方便的获取URL中的参数。constgetParamByUrl=(key)=>{consturl=newURL(location.href)returnurl.searchParams.get(key)}深拷贝对象深拷贝对象很简单,先把对象转成字符串,再转它到一个对象就是这样。constdeepCopy=obj=>JSON.parse(JSON.stringify(obj))除了使用JSONAPI之外,还有一个更新的structuredCloneAPI用于深度复制对象,但并非所有浏览器都支持它。structuredClone(obj)等待函数JavaScript提供了一个setTimeout函数,但是它不返回一个Promise对象,所以我们不能使用async来作用于这个函数,但是我们可以封装等待函数。constwait=(ms)=>newPromise((resolve)=>setTimeout(resolve,ms))constasyncFn=async()=>{awaitwait(1000)console.log('等待异步函数结束执行')}asyncFn()
