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}")
}
}
}
发表评论