In daily development, we will accumulate some commonly used code snippets, which can be directly copied and pasted into various projects for use, which is very convenient. If you have taken over other people's projects, you may notice that the same tools and methods exist in some projects. These are common code snippets accumulated by previous developers.
Now that the front-end community has matured, excellent libraries such as lodash and dayjs can meet our needs for processing arrays, dates, etc. This article will not repeat these common fragments.
When hiding the pop-up box or collapsing the drop-down menu, use the contains method instead of checking layer by layer.
// 代码示例 (此处省略)
To view the homepage or code repository of a third-party library, you can use these npm commands:
npm home PACKAGE_NAME
npm home react
npm repo PACKAGE_NAME
npm repo react
In addition to removing the listener in the event function, you can also use the once parameter.
// 代码示例 (此处省略)
In scenarios such as displaying audio/video duration, you can format seconds like this:
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));
To display relative time like "just now", you can try the timeago.js library.
No need to use query-string library, use URLSearchParams API directly:
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));
When opening external links, set rel="noopener noreferrer" to avoid security risks.
<a href="https://example.com" rel="noopener noreferrer" target="_blank">打开</a>
function openNewTab() { window.open("https://example.com", "newTab", "noopener,noreferrer"); }
Use the readAsDataURL method of the FileReader API to display the uploaded image.
// 代码示例 (此处省略)
Using the download attribute of the tag can trigger a download, but it has some limitations.
<a download="" href="https://www.php.cn/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); }
You can also set response headers on the server side, or on the browser side using Blob and 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);
Cache function results for complex calculations.
const memoize = (fn) => ( (cache = Object.create(null)) => (arg) => cache[arg] || (cache[arg] = fn(arg)) )(); // 代码示例 (此处省略)
Use CSS to truncate text to ellipses, on single or multiple lines.
.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; }
Use CSS selectors to target specific elements.
li:nth-child(-n + 3) { text-decoration: underline; } // 代码示例 (此处省略)
Customize scroll bar styles using CSS or third-party libraries like better-scroll.
// 代码示例 (此处省略)
Use the maximum remainder method to ensure that the percentages sum to 1.
// 代码示例 (此处省略)
Limit the number of concurrent requests when making a large number of requests.
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));
Use this code to generate a unique identifier.
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));
Prevent body scrolling when opening the modal.
<a href="https://example.com" rel="noopener noreferrer" target="_blank">打开</a>
Original link: https://www.php.cn/link/d9d838896ca0a5e16e7efa2439943fbd
The above is the detailed content of Front-End Code Snippets Worth Checking Out. For more information, please follow other related articles on the PHP Chinese website!