1. bottomVisible:检查页面底部是否可见

  1. const bottomVisible = () =>
  2. document.documentElement.clientHeight + window.scrollY >= (document.documentElement.scrollHeight || document.documentElement.clientHeight);
  3. bottomVisible(); // true

2. Create Directory:检查创建目录

此代码段调用fs模块的existsSync()检查目录是否存在,如果不存在,则mkdirSync()创建该目录。

  1. const fs = require('fs');
  2. const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
  3. createDirIfNotExists('test');

3. currentURL:返回当前链接url

  1. const currentURL = () => window.location.href;
  2. currentURL(); // 'https://juejin.im'

4. distance:返回两点间的距离

该代码段通过计算欧几里得距离来返回两点之间的距离。

  1. const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
  2. distance(1, 1, 2, 3); // 2.23606797749979

5. elementContains:检查是否包含子元素

此代码段检查父元素是否包含子元素。

  1. const elementContains = (parent, child) => parent !== child && parent.contains(child);
  2. elementContains(document.querySelector('head'), document.querySelector('title')); // true
  3. elementContains(document.querySelector('body'), document.querySelector('body')); // false

6. getStyle:返回指定元素的生效样式

  1. const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];
  2. getStyle(document.querySelector('p'), 'font-size'); // '16px'

7. getType:返回值或变量的类型名

  1. const getType = v =>v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
  2. getType(new Set([1, 2, 3])); // 'set'
  3. getType([1, 2, 3]); // 'array'

8. hasClass:校验指定元素的类名

  1. const hasClass = (el, className) => el.classList.contains(className); hasClass(document.querySelector('p.special'), 'special'); // true

9. hide:隐藏所有的指定标签

  1. const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));
  2. hide(document.querySelectorAll('img')); // 隐藏所有<img>标签

10. httpsRedirectHTTP 跳转 HTTPS

  1. const httpsRedirect = () => {
  2. if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
  3. };
  4. httpsRedirect(); // 若在`http://www.baidu.com`, 则跳转到`https://www.baidu.com`

11. insertAfter:在指定元素之后插入新元素

  1. const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
  2. // <div id="myId">...</div> <p>after</p>
  3. insertAfter(document.getElementById('myId'), '<p>after</p>');

12. insertBefore:在指定元素之前插入新元素

  1. const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
  2. insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>

13. isBrowser:检查是否为浏览器环境

此代码段可用于确定当前运行时环境是否为浏览器。这有助于避免在服务器(节点)上运行前端模块时出错。

  1. const isBrowser = () => ![typeof window, typeof document].includes('undefined');
  2. isBrowser(); // true (browser)
  3. isBrowser(); // false (Node)

14. isBrowserTab:检查当前标签页是否活动

  1. const isBrowserTabFocused = () => !document.hidden;
  2. isBrowserTabFocused(); // true

15. nodeListToArray:转换nodeList为数组

  1. const nodeListToArray = nodeList => [...nodeList];
  2. nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]

16. Random Hexadecimal Color Code:随机十六进制颜色

  1. const randomHexColorCode = () => {
  2. let n = (Math.random() * 0xfffff * 1000000).toString(16);
  3. return '#' + n.slice(0, 6);
  4. };
  5. randomHexColorCode(); // "#e34155"

17. scrollToTop:平滑滚动至顶部

该代码段可用于平滑滚动到当前页面的顶部。

  1. const scrollToTop = () => {
  2. const c = document.documentElement.scrollTop || document.body.scrollTop;
  3. if (c > 0) {
  4. window.requestAnimationFrame(scrollToTop);
  5. window.scrollTo(0, c - c / 8);
  6. }
  7. };
  8. scrollToTop();

18. smoothScroll:滚动到指定元素区域

该代码段可将指定元素平滑滚动到浏览器窗口的可见区域。

  1. const smoothScroll = element =>
  2. document.querySelector(element).scrollIntoView({
  3. behavior: 'smooth'
  4. });
  5. smoothScroll('#fooBar');
  6. smoothScroll('.fooBar');

19. detectDeviceType:检测移动/PC设备

  1. const detectDeviceType = () =>
  2. /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  3. ? 'Mobile'
  4. : 'Desktop';

20. getScrollPosition:返回当前的滚动位置

默认参数为windowpageXOffset(pageYOffset)为第一选择,没有则用scrollLeft(scrollTop)

  1. const getScrollPosition = (el = window) => ({
  2. x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  3. y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
  4. });
  5. getScrollPosition(); // {x: 0, y: 200}