7 种常用的 JS 代码片段
日常开发中,我们经常会用到很多通用的 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=100
const name = getQueryByName('name') // fatfish
const age = getQueryByName('age') // 100
const gender = getQueryByName('gender') // null
03:平滑滚动至页面顶部
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还是iOS
function 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() // 0
06:格式化货币
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}")
}
}
}