日常開發中,我們都會累積一些常用的程式碼片段,可以直接複製貼上到各種專案中使用,非常方便。如果你接手過別人的項目,可能會注意到一些專案中存在相同的工具方法,這些就是先前開發者累積的常用程式碼片段。
如今前端社群發展成熟,lodash、dayjs 等優秀函式庫能滿足我們處理陣列、日期等的需求,本文不會重複這些常見的片段。
隱藏彈出框或收起下拉式功能表時,使用 contains 方法取代逐層檢查。
// 代码示例 (此处省略)
查看第三方函式庫的首頁或程式碼倉庫,可以使用這些 npm 指令:
npm home PACKAGE_NAME
npm home react
npm repo PACKAGE_NAME
npm repo react
除了在事件函數中移除監聽器,還可以使用 once 參數。
// 代码示例 (此处省略)
在顯示音訊/視訊時長等場景下,可以這樣格式化秒數:
const formatSeconds = (s) => [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(":").replace(/\b(\d)\b/g, "0"); const seconds = 3661; console.log(formatSeconds(seconds));
要顯示類似「剛剛」的相對時間,可以嘗試 timeago.js 函式庫。
無需使用 query-string 函式庫,直接使用 URLSearchParams API:
const getUrlParams = (query) => Array.from(new URLSearchParams(query)).reduce( (p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }), {} ); const query = "?a=1&b=2&a=3"; console.log(getUrlParams(query));
開啟外部連結時,設定 rel="noopener noreferrer" 以避免安全風險。
<a href="https://example.com" rel="noopener noreferrer" target="_blank">打开</a>
function openNewTab() { window.open("https://example.com", "newTab", "noopener,noreferrer"); }
使用 FileReader API 的 readAsDataURL 方法顯示上傳的圖片。
// 代码示例 (此处省略)
使用 標籤的 download 屬性可以觸發下載,但它有一些限制。
<a download="" href="//m.sbmmt.com/link/8b89afaf8e00e0a46ea4d76ac473b1a2">下载</a>
function download(url) { const link = document.createElement("a"); link.download = "file name"; link.href = url; document.body.appendChild(link); link.click(); document.body.removeChild(link); }
你也可以在伺服器端設定回應頭,或是在瀏覽器端使用 Blob 和 createObjectURL。
const data = JSON.stringify({ message: "Hello" }); const blob = new Blob([data], { type: "application/json" }); const url = window.URL.createObjectURL(blob); download(url); window.URL.revokeObjectURL(url);
為複雜的計算快取函數結果。
const memoize = (fn) => ( (cache = Object.create(null)) => (arg) => cache[arg] || (cache[arg] = fn(arg)) )(); // 代码示例 (此处省略)
使用 CSS 將文字截斷為省略號,適用於單行或多行。
.truncate-single { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .truncate-multi { display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; overflow: hidden; }
使用 CSS 選擇器定位特定元素。
li:nth-child(-n + 3) { text-decoration: underline; } // 代码示例 (此处省略)
使用 CSS 或 better-scroll 等第三方函式庫自訂捲軸樣式。
// 代码示例 (此处省略)
使用最大餘數法確保百分比總和等於 1。
// 代码示例 (此处省略)
在進行大量請求時,限制並發請求數。
const formatSeconds = (s) => [parseInt(s / 60 / 60), parseInt((s / 60) % 60), parseInt(s % 60)].join(":").replace(/\b(\d)\b/g, "0"); const seconds = 3661; console.log(formatSeconds(seconds));
使用此代碼生成唯一標識符。
const getUrlParams = (query) => Array.from(new URLSearchParams(query)).reduce( (p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }), {} ); const query = "?a=1&b=2&a=3"; console.log(getUrlParams(query));
打開模態框時阻止 body 滾動。
<a href="https://example.com" rel="noopener noreferrer" target="_blank">打开</a>
原文鏈接://m.sbmmt.com/link/d9d838896ca0a5e16e7efa2439943fbd
以上是值得檢查的前端程式碼片段的詳細內容。更多資訊請關注PHP中文網其他相關文章!