01:将内容复制到剪贴板
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:格式化货币
const formatMoney = (money) => {
return money.toLocaleString()
}
formatMoney(123456789) // '123,456,789'
formatMoney(123456789.123) // '123,456,789.123'
formatMoney(123) // '123'
06:进入和退出全屏
// 进入全屏
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}")
}
}
}