日常开发中,我们经常会用到很多通用的 JS 代码,比如:复制内容、从 URL 中获取指定参数 等
这些代码通常有固定实现,即:代码片段
所以,为了方便大家的开发,今天咱们就来看看常用的 7 种代码片段
通过按钮,将指定 dom 中的内容复制到用户的剪贴板
const copyToClipboard = (content) => {
const textarea = document.createElement("textarea")
textarea.value = content
document.body.appendChild(textarea)
textarea.select()
document.execCommand("Copy")
textarea.remove()
}
这应该是一个非常常见的操作,之前经常会使用 正则来完成,现在有了更简单的方式:
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
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop
if (c > 0) {
window.requestAnimationFrame(scrollToTop)
window.scrollTo(0, c - c / 8)
}
}
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 }
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
const formatMoney = (money) => {
return money.toLocaleString()
}
formatMoney(123456789) // '123,456,789'
formatMoney(123456789.123) // '123,456,789.123'
formatMoney(123) // '123'
// 进入全屏
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}")
}
}
}