简化你的工作,7种常用的JS代码片段

程序员咋不秃头 2024-06-21 10:05:46

日常开发中,我们经常会用到很多通用的 JS 代码,比如:复制内容、从 URL 中获取指定参数 等

这些代码通常有固定实现,即:代码片段。

所以,为了方便大家的开发,今天咱们就来看看常用的 7 种代码片段

01:将内容复制到剪贴板

通过按钮,将指定 dom 中的内容复制到用户的剪贴板

const copyToClipboard = (content) => { const textarea = document.createElement("textarea") textarea.value = content document.body.appendChild(textarea) textarea.select() document.execCommand("Copy") textarea.remove()}02:使用URLSearchParams获取URL的搜索参数

这应该是一个非常常见的操作,之前经常会使用 正则来完成,现在有了更简单的方式:

const getQueryByName = (name) => { const query = new URLSearchParams(location.search) return decodeURIComponent(query.get(name))}// url: https://sunday.com/?name=fatfish&age=100const name = getQueryByName('name') // fatfishconst age = getQueryByName('age') // 100const gender = getQueryByName('gender') // null03:平滑滚动至页面顶部const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop if (c > 0) { window.requestAnimationFrame(scrollToTop) window.scrollTo(0, c - c / 8) }}04:获取当前页面滚动距离const getScrollPosition = (el = window) => ({ x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,})getScrollPosition() // { x: 0, y: 215 }05:判断当前设备是Andoird还是iOSfunction getOSType() { let u = navigator.userAgent, app = navigator.appVersion let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1 let isIOS = !!u.match(/\(i[^]+( U)? CPU.+Mac OS X/) if (isIOS) { return 0 } else if (isAndroid) { return 1 } else { return 2 }}getOSType() // 006:格式化货币const formatMoney = (money) => { return money.toLocaleString()}formatMoney(123456789) // '123,456,789'formatMoney(123456789.123) // '123,456,789.123'formatMoney(123) // '123'07:进入和退出全屏// 进入全屏function fullScreen() { let el = document.documentElement let rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullScreen //typeof rfs != "undefined" && rfs if (rfs) { rfs.call(el) } else if (typeof window.ActiveXObject !== "undefined") { let wscript = new ActiveXObject("WScript.Shell") if (wscript != null) { wscript.SendKeys("{F11}") } }}// 退出全屏function exitScreen() { let el = document let cfs = el.cancelFullScreen || el.webkitCancelFullScreen || el.mozCancelFullScreen || el.exitFullScreen //typeof cfs != "undefined" && cfs if (cfs) { cfs.call(el) } else if (typeof window.ActiveXObject !== "undefined") { let wscript = new ActiveXObject("WScript.Shell") if (wscript != null) { wscript.SendKeys("{F11}") } }}
1 阅读:4

程序员咋不秃头

简介:感谢大家的关注