簡化你的工作,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}") } }}
0 阅读:2

程序員咋不禿頭

簡介:感謝大家的關注