es6開發(fā)常用技巧

1.如何隱藏所有指定的元素

const hide = (el) => Array.from(el).forEach(e => (e.style.display = 'none'));
// 事例: 隱藏頁(yè)面上所有`<p>`元素
hide(document.querySelectorALL('p'))

2.如何檢查元素是否具有指定的類湿右?

頁(yè)面DOM里面的每個(gè)節(jié)點(diǎn)上都有一個(gè) $\color{#FF0000}{classList}$對(duì)象,程序員可以使用里面的方法新增票髓、刪除、修改铣耘、查詢節(jié)點(diǎn)上的class類洽沟。

const hasClass = (el, className) => el.classList.contains(className)

// 事例
hasClass(document.querySelector('p.special'), 'spec') // true

3.如何切換一個(gè)元素的類?

const toggleClass = (el, className) => el.classList.toggle(className)

// 事例 移除 p 具有類`special`的 speci 類
toggleClass(document.querySelector('p.special'), 'speci')

4.如何獲取當(dāng)前頁(yè)面的滾動(dòng)位置?

const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

// 事例
getScrollPosition(); // {x: 0, y: 200}

5.如何平滑滾動(dòng)到頁(yè)面頂部

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
}

// 事例
scrollToTop()

$\color{#FF0000}{window.requestAnimationFrame()}$ 告訴瀏覽器——你希望執(zhí)行一個(gè)動(dòng)畫蜗细,并且要求瀏覽器在下次重繪之前調(diào)用指定的回調(diào)函數(shù)更新動(dòng)畫裆操。該方法需要傳入一個(gè)回調(diào)函數(shù)作為參數(shù),該回調(diào)函數(shù)會(huì)在瀏覽器下一次重繪之前執(zhí)行炉媒。
$\color{#FF0000}{requestAnimationFrame:}$
優(yōu)勢(shì):由系統(tǒng)決定回調(diào)函數(shù)的執(zhí)行時(shí)機(jī)踪区。60Hz的刷新頻率,那么每次刷新的間隔中會(huì)執(zhí)行一次回調(diào)函數(shù)橱野,不會(huì)引起丟幀朽缴,不會(huì)卡頓。

6.如何檢查父元素是否包含子元素水援?

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

7.如何檢查指定的元素在視口中是否可見?

const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
  const { top, left, bottom, right } = el.getBoundingClientRect();
  const { innerHeight, innerWidth } = window;
  return partiallyVisible
    ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
        ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
    : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};

// 事例
elementIsVisibleInViewport(el); // 需要左右可見
elementIsVisibleInViewport(el, true); // 需要全屏(上下左右)可以見

8.如何獲取元素中的所有圖像茅郎?

const getImages = (el, includeDuplicates = false) => {
  const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
  return includeDuplicates ? images : [...new Set(images)];
};

// 事例:includeDuplicates 為 true 表示需要排除重復(fù)元素
getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']
getImages(document, false); // ['image1.jpg', 'image2.png', '...']

9.如何確定設(shè)備是移動(dòng)設(shè)備還是臺(tái)式機(jī)/筆記本電腦蜗元?

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

// 事例
detectDeviceType(); // "Mobile" 移動(dòng)設(shè)備 or "Desktop" 臺(tái)式機(jī)

10.如何創(chuàng)建一個(gè)包含當(dāng)前URL參數(shù)的對(duì)象盆佣?

const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );

// 事例
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}

11.如何將一組表單元素轉(zhuǎn)化為對(duì)象刘急?

const formToObject = form =>
  Array.from(new FormData(form)).reduce(
    (acc, [key, value]) => ({
      ...acc,
      [key]: value
    }),
    {}
  );

// 事例
formToObject(document.querySelector('#form')); 
// { email: 'test@email.com', name: 'Test Name' }

12.如何從對(duì)象檢索給定選擇器指示的一組屬性?

const get = (from, ...selectors) =>
  [...selectors].map(s =>
    s
      .replace(/\[([^\[\]]*)\]/g, '.$1.')
      .split('.')
      .filter(t => t !== '')
      .reduce((prev, cur) => prev && prev[cur], from)
  );
const obj = { selector: { to: { val: 'val to select' } }, target: [1, 2, { a: 'test' }] };

// Example
get(obj, 'selector.to.val', 'target[0]', 'target[2].a'); 
// ['val to select', 1, 'test']

13.如何在等待指定時(shí)間后調(diào)用提供的函數(shù)扁达?

const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
delay(
  function(text) {
    console.log(text);
  },
  1000,
  'later'
); 

// 1秒后打印 'later'

14.如何在給定元素上觸發(fā)特定事件且能選擇地傳遞自定義數(shù)據(jù)掌敬?

const triggerEvent = (el, eventType, detail) =>
  el.dispatchEvent(new CustomEvent(eventType, { detail }));

// 事例
triggerEvent(document.getElementById('myId'), 'click');
triggerEvent(document.getElementById('myId'), 'click', { username: 'bob' });

自定義事件的函數(shù)有$\color{#FF0000}{Event}$ 惯豆、$\color{#FF0000}{CustomEvent}$$\color{#FF0000}{dispatchEvent}$

// 向 window派發(fā)一個(gè)resize內(nèi)置事件
window.dispatchEvent(new Event('resize'))
 

// 直接自定義事件,使用 Event 構(gòu)造函數(shù):
var event = new Event('build');
var elem = document.querySelector('#id')
// 監(jiān)聽事件
elem.addEventListener('build', function (e) { ... }, false);
// 觸發(fā)事件.
elem.dispatchEvent(event);

$\color{#FF0000}{CustomEvent}$ 可以創(chuàng)建一個(gè)更高度自定義事件奔害,還可以附帶一些數(shù)據(jù)楷兽,具體用法如下:

var myEvent = new CustomEvent(eventname, options);
其中 options 可以是:
{
  detail: {
    ...
  },
  bubbles: true,    //是否冒泡
  cancelable: false //是否取消默認(rèn)事件
}

其中 $\color{#FF0000}{detail}$ 可以存放一些初始化的信息,可以在觸發(fā)的時(shí)候調(diào)用华临。其他屬性就是定義該事件是否具有冒泡等等功能芯杀。

內(nèi)置的事件會(huì)由瀏覽器根據(jù)某些操作進(jìn)行觸發(fā),自定義的事件就需要人工觸發(fā)雅潭。 $\color{#FF0000}{dispatchEvent}$ 函數(shù)就是用來(lái)觸發(fā)某個(gè)事件:

element.dispatchEvent(customEvent);

上面代碼表示揭厚,在 $\color{#FF0000}{element}$ 上面觸發(fā) $\color{#FF0000}{customEvent}$ 這個(gè)事件。

// add an appropriate event listener
obj.addEventListener("cat", function(e) { process(e.detail) });
 
// create and dispatch the event
var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}});
obj.dispatchEvent(event);
使用自定義事件需要注意兼容性問(wèn)題扶供,而使用 jQuery 就簡(jiǎn)單多了:

// 綁定自定義事件
$(element).on('myCustomEvent', function(){});
 
// 觸發(fā)事件
$(element).trigger('myCustomEvent');
// 此外筛圆,你還可以在觸發(fā)自定義事件時(shí)傳遞更多參數(shù)信息:
 
$( "p" ).on( "myCustomEvent", function( event, myName ) {
  $( this ).text( myName + ", hi there!" );
});
$( "button" ).click(function () {
  $( "p" ).trigger( "myCustomEvent", [ "John" ] );
});

15.如何從元素中移除事件監(jiān)聽器?

const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts);

const fn = () => console.log('!');
document.body.addEventListener('click', fn);
off(document.body, 'click', fn); 

16.如何獲得給定毫秒數(shù)的可讀格式?

const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
    .join(', ');
};

// 事例
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); 
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'

17.如何獲得兩個(gè)日期之間的差異(以天為單位)椿浓?

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);

// 事例
getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9

18.如何向傳遞的URL發(fā)出GET請(qǐng)求

const httpGet = (url, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send();
};

httpGet(
  'https://jsonplaceholder.typicode.com/posts/1',
  console.log
); 

// {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}

19.如何對(duì)傳遞的URL發(fā)出POST請(qǐng)求

const httpPost = (url, data, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send(data);
};

const newPost = {
  userId: 1,
  id: 1337,
  title: 'Foo',
  body: 'bar bar bar'
};
const data = JSON.stringify(newPost);
httpPost(
  'https://jsonplaceholder.typicode.com/posts',
  data,
  console.log
); 

// {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}

20.如何為指定選擇器創(chuàng)建具有指定范圍太援,步長(zhǎng)和持續(xù)時(shí)間的計(jì)數(shù)器漾岳?

const counter = (selector, start, end, step = 1, duration = 2000) => {
  let current = start,
    _step = (end - start) * step < 0 ? -step : step,
    timer = setInterval(() => {
      current += _step;
      document.querySelector(selector).innerHTML = current;
      if (current >= end) document.querySelector(selector).innerHTML = end;
      if (current >= end) clearInterval(timer);
    }, Math.abs(Math.floor(duration / (end - start))));
  return timer;
};

// 事例
counter('#my-id', 1, 1000, 5, 2000); 
// 讓 `id=“my-id”`的元素創(chuàng)建一個(gè)2秒計(jì)時(shí)器

21.如何將字符串復(fù)制到剪貼板?

  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};

// 事例
copyToClipboard('Lorem ipsum'); 
// 'Lorem ipsum' copied to clipboard

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末粉寞,一起剝皮案震驚了整個(gè)濱河市尼荆,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌唧垦,老刑警劉巖捅儒,帶你破解...
    沈念sama閱讀 217,277評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異振亮,居然都是意外死亡巧还,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門坊秸,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)麸祷,“玉大人,你說(shuō)我怎么就攤上這事褒搔〗纂梗” “怎么了?”我有些...
    開封第一講書人閱讀 163,624評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵星瘾,是天一觀的道長(zhǎng)走孽。 經(jīng)常有香客問(wèn)我,道長(zhǎng)琳状,這世上最難降的妖魔是什么磕瓷? 我笑而不...
    開封第一講書人閱讀 58,356評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮念逞,結(jié)果婚禮上困食,老公的妹妹穿的比我還像新娘。我一直安慰自己翎承,他們只是感情好硕盹,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,402評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著审洞,像睡著了一般莱睁。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上芒澜,一...
    開封第一講書人閱讀 51,292評(píng)論 1 301
  • 那天仰剿,我揣著相機(jī)與錄音,去河邊找鬼痴晦。 笑死南吮,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的誊酌。 我是一名探鬼主播部凑,決...
    沈念sama閱讀 40,135評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼露乏,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了涂邀?” 一聲冷哼從身側(cè)響起瘟仿,我...
    開封第一講書人閱讀 38,992評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎比勉,沒(méi)想到半個(gè)月后劳较,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,429評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡浩聋,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,636評(píng)論 3 334
  • 正文 我和宋清朗相戀三年观蜗,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片衣洁。...
    茶點(diǎn)故事閱讀 39,785評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡墓捻,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出坊夫,到底是詐尸還是另有隱情砖第,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評(píng)論 5 345
  • 正文 年R本政府宣布践樱,位于F島的核電站厂画,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏拷邢。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,092評(píng)論 3 328
  • 文/蒙蒙 一屎慢、第九天 我趴在偏房一處隱蔽的房頂上張望瞭稼。 院中可真熱鬧,春花似錦腻惠、人聲如沸环肘。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)悔雹。三九已至,卻和暖如春欣喧,著一層夾襖步出監(jiān)牢的瞬間腌零,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工唆阿, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留益涧,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,891評(píng)論 2 370
  • 正文 我出身青樓驯鳖,卻偏偏與公主長(zhǎng)得像闲询,于是被迫代替她去往敵國(guó)和親久免。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,713評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容