在我们的开发人员工作流程中,我们经常遇到可能只需要几行代码即可解决的具有挑战性的问题。在本文中,我尝试编写一些有用的代码片段,这些代码片段可以在处理 URL、DOM、事件、日期、用户偏好等时为你提供帮助。
整理学习这些的主要标准就是它的实用性,希望你能从中找到一些有价值的东西,可以应用到你未来的代码库中。
1.如何获取基础 URL?
const getBaseURL = url => url.replace(/[?#].*$/, '');
getBaseURL('http://url.com/page?name=Adam&surname=Smith');
// 'http://url.com/page'
- 1.
- 2.
- 3.
2.如何判断网址是否为绝对网址?
const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false
- 1.
- 2.
- 3.
- 4.
3.如何获取URL参数作为对象?
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => (
(a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a
),
{}
);
getURLParameters('google.com'); // {}
getURLParameters('http://url.com/page?name=Adam&surname=Smith');
// {name: 'Adam', surname: 'Smith'}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
4.如何检查元素是否包含另一个元素?
const elementContains = (parent, child) =>
parent !== child && parent.contains(child);
elementContains(
document.querySelector('head'),
document.querySelector('title')
);
// true
elementContains(document.querySelector('body'), document.querySelector('body'));
// false
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
5.如何获取元素的所有祖先?
const getAncestors = el => {
let ancestors = [];
while (el) {
ancestors.unshift(el);
el = el.parentNode;
}
return ancestors;
};
getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
6.如何平滑滚动元素进入视图?
const smoothScroll = element =>
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
smoothScroll('#fooBar'); // scrolls smoothly to the element with the id fooBar
smoothScroll('.fooBar');
// scrolls smoothly to the first element with a class of fooBar
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
7.如何处理元素外的点击?
const onClickOutside = (element, callback) => {
document.addEventListener('click', e => {
if (!element.contains(e.target)) callback();
});
};
onClickOutside('#my-element', () => console.log('Hello'));
// Will log 'Hello' whenever the user clicks outside of #my-element
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
8.如何生成UUID?
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(
c ^
(crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
).toString(16)
);
UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d'
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
9.如何获取选中的文本?
const getSelectedText = () => window.getSelection().toString();
getSelectedText(); // 'Lorem ipsum'
- 1.
- 2.
10.如何将文本复制到剪贴板?
const copyToClipboard = str => {
if (navigator && navigator.clipboard && navigator.clipboard.writeText)
return navigator.clipboard.writeText(str);
return Promise.reject('The Clipboard API is not available.');
};
- 1.
- 2.
- 3.
- 4.
- 5.
QQ7Ies" id="h6f20189-w3QQ7Ies">11.如何给 HTML 元素添加样式?
const addStyles = (el, styles) => Object.assign(el.style, styles);
addStyles(document.getElementById('my-element'), {
background: 'red',
color: '#ffff00',
fontSize: '3rem'
});
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
12.如何切换全屏模式?
const fullscreen = (mode = true, el = 'body') =>
mode
? document.querySelector(el).requestFullscreen()
: document.exitFullscreen();
fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
13.如何检测Caps Lock是否开启?
<form>
<label for="username">Username:</label>
<input id="username" name="username">
<label for="password">Password:</label>
<input id="password" name="password" type="password">
<span id="password-message" style="display: none">Caps Lock is on</span>
</form>
const el = document.getElementById('password');
const msg = document.getElementById('password-message');
el.addEventListener('keyup', e => {
msg.style = e.getModifierState('CapsLock')
? 'display: block'
: 'display: none';
});
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
14.如何查看日期是否有效?
const isDateValid = (val) => !Number.isNaN(new Date(val).valueOf());
isDateValid('December 17, 1995 03:24:00'); // true
isDateValid('1995-12-17T03:24:00'); // true
isDateValid('1995-12-17 T03:24:00'); // false
isDateValid('Duck'); // false
isDateValid(1995, 11, 17); // true
isDateValid(1995, 11, 17, 'Duck'); // false
isDateValid({}); // false
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
15.如何从Date中获取冒号时间?
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
getColonTimeFromDate(new Date()); // '08:38:00'
- 1.
- 2.
16.如何从 Date 生成 UNIX 时间戳?
const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000);
getTimestamp(); // 1602162242
- 1.
- 2.
17、如何查看当前用户的首选语言?
const detectLanguage = (defaultLang = 'en-US') =>
navigator.language ||
(Array.isArray(navigator.languages) && navigator.languages[0]) ||
defaultLang;
detectLanguage(); // 'nl-NL'
- 1.
- 2.
- 3.
- 4.
- 5.
18、如何查看用户偏好的配色方案?
const prefersDarkColorScheme = () =>
window &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
prefersDarkColorScheme(); // true
- 1.
- 2.
- 3.
- 4.
- 5.
19.如何查看设备是否支持触摸事件?
const supportsTouchEvents = () =>
window && 'ontouchstart' in window;
supportsTouchEvents(); // true
- 1.
- 2.
- 3.