URL
URL
?const getBaseURL = url => url.replace(/[?#].*$/, '');
getBaseURL('http://url.com/page?name=Adam&surname=Smith');
// 'http://url.com/page'
URL
是否是绝对的?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
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'}
URL
对象const url = new URL("https://example.com/login?user=someguy&page=news");
url.origin
// "https://example.com"
url.host
// "example.com"
url.protocol
// "https:"
url.pathname
// "/login"
url.searchParams.get('user')
// "someguy"
DOM
const elementContains = (parent, child) =>
parent !== child && parent.contains(child);
elementContains(
document.querySelector('head'),
document.querySelector('title')
);
// true
elementContains(document.querySelector('body'), document.querySelector('body'));
const getAncestors = el => {
let ancestors = [];
while (el) {
ancestors.unshift(el);
el = el.parentNode;
}
return ancestors;
};
getAncestors(document.querySelector('nav'));
// [document, html, body, header, nav]
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
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
HTML
元素添加样式?const addStyles = (el, styles) => Object.assign(el.style, styles);
addStyles(document.getElementById('my-element'), {
background: 'red',
color: '#ffff00',
fontSize: '3rem'
});
const getSelectedText = () => window.getSelection().toString();
getSelectedText(); // 'Lorem ipsum'
const copyToClipboard = str => {
if (navigator && navigator.clipboard && navigator.clipboard.writeText)
return navigator.clipboard.writeText(str);
return Promise.reject('The Clipboard API is not available.');
};
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
Date
中获取冒号时间?const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);
getColonTimeFromDate(new Date()); // '08:38:00'
const detectLanguage = (defaultLang = 'en-US') =>
navigator.language ||
(Array.isArray(navigator.languages) && navigator.languages[0]) ||
defaultLang;
detectLanguage(); // 'nl-NL'
const prefersDarkColorScheme = () =>
window &&
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches;
prefersDarkColorScheme(); // true
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'
const fullscreen = (mode = true, el = 'body') =>
mode
? document.querySelector(el).requestFullscreen()
: document.exitFullscreen();
fullscreen(); // Opens `body` in fullscreen mode
fullscreen(false); // Exits fullscreen mode
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';
});
const supportsTouchEvents = () =>
window && 'ontouchstart' in window;
supportsTouchEvents(); // true
本人每篇文章都是一字一句码出来,希望对大家有所帮助,多提提意见。顺手来个三连击,点赞👍收藏💖关注?,一起加油?