解決常見JS問題的19個實用 ES6 片段

在我們的開發人員工作流程中,我們經常會遇到具有挑戰性的問題,這些問題可能只需要幾行代碼就可以解決。在本文中,我試圖編譯有用的片段,這些片段可能會在您處理 URL、DOM、事件、日期、用戶首選項等時爲您提供幫助。

 

所有的片段都是精心挑選出來的。這是一個很棒的資源,我強烈建議您去查看更多內容。策劃這些的主要標準是實際可用性。希望您會發現一些有價值的東西,您可以將其應用到您未來的代碼庫中。


1、如何獲取base URL?

const getBaseURL = url => url.replace(/[?#].*$/, '');

getBaseURL('http://url.com/page?name=Adam&surname=Smith');
// 'http://url.com/page'

2、如何判斷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

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'}

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

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]

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

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

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'

9、如何獲取選中的文字?

const getSelectedText = () => window.getSelection().toString();

getSelectedText(); // 'Lorem ipsum'

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.');
};

11.如何給HTML元素添加樣式?

const addStyles = (el, styles) => Object.assign(el.style, styles);

addStyles(document.getElementById('my-element'), {
 background: 'red',
 color: '#ffff00',
 fontSize: '3rem'
});

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

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';
});

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

15. 如何從 Date 中獲取冒號時間?

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // '08:38:00'

16. 如何從 Date 生成 UNIX 時間戳?

const getTimestamp = (date = new Date()) => Math.floor(date.getTime() / 1000);

getTimestamp(); // 1602162242

17、如何查看當前用戶的首選語言?

const detectLanguage = (defaultLang = 'en-US') =>
 navigator.language ||
(Array.isArray(navigator.languages) && navigator.languages[0]) ||
 defaultLang;

detectLanguage(); // 'nl-NL'

18. 如何查看用戶偏好的配色方案?

const prefersDarkColorScheme = () =>
 window &&
 window.matchMedia &&
 window.matchMedia('(prefers-color-scheme: dark)').matches;

prefersDarkColorScheme(); // true

19. 如何查看設備是否支持觸摸事件?

const supportsTouchEvents = () =>
 window && 'ontouchstart' in window;

supportsTouchEvents(); // true

寫作一直是我的熱情所在,它讓我樂於幫助和啓發人們。如有任何疑問,請隨時與我們聯繫!如果對你有幫助,記得點贊支持!

如果你正在學前端,可以關注我們!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章