歡迎您光臨本站 註冊首頁

24個ES6方法解決JS實際開發問題(小結)

←手機掃碼閱讀     lousu-xi @ 2020-06-12 , reply:0

本文主要介紹 24 中 es6 方法,這些方法都挺實用的,本本請記好,時不時翻出來看看。

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

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

 

2、如何檢查元素是否具有指定的類 ?
 頁面DOM裡的每個節點上都有一個 classList 對象,程序員可以使用裡面的方法新增、刪除、修改節點上的CSS類;使用 classList,程序員還可以用它來判斷某個節點是否被賦予了某個CSS類;
 

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

 

3.如何切換一個元素的類 ?
 

  const toggleClass = (el, className) => el.classList.toggle(className)    // 事例 移除 p 具有類`special`的 special 類  toggleClass(document.querySelector('p.special'), 'special')

 

4.如何獲取當前頁面的滾動位置?
 

  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.如何平滑滾動到頁面頂部?
 

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

 

window.requestAnimationFrame()  告訴瀏覽器――你希望執行一個動畫,並且要求瀏覽器在下次重繪之前調用指定的回調函數更新動畫。該方法需要傳入一個回調函數作為參數,該回調函數會在瀏覽器下一次重繪之前執行。
 

requestAnimationFrame:優勢:由系統決定回調函數的執行時機。60Hz的刷新頻率,那麼每次刷新的間隔中會執行一次回調函數,不會引起丟幀,不會卡頓。

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 表示需要排除重複元素  getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']  getImages(document, false); // ['image1.jpg', 'image2.png', '...']

 

9. 如何確定設備是移動設備還是臺式機/筆記本電腦 ?
 

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

 

10.How to get the current URL ?
 

   const currentURL = () => window.location.href    // 事例  currentURL() // 'https://google.com'

 

11.如何創建一個包含當前URL參數的對象 ?
 

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

 

12.如何將一組表單子元素轉化為對象 ?
 

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

 

13.如何從對象檢索給定選擇器指示的一組屬性 ?
 

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

 

14.如何在等待指定時間後調用提供的函數 ? 

  const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);  delay(   function(text) {    console.log(text);   },   1000,   'later'  );     // 1秒後打印 'later'

 

15.如何在給定元素上觸發特定事件且能選擇地傳遞自定義數據 ?
 

  const triggerEvent = (el, eventType, detail) =>   el.dispatchEvent(new CustomEvent(eventType, { detail }));    // 事例  triggerEvent(document.getElementById('myId'), 'click');  triggerEvent(document.getElementById('myId'), 'click', { username: 'bob' });

 

自定義事件的函數有 Event、CustoEvent 和 dispatchEvent;
 

  // 向 window 派發一個resize內置事件  window.dispatchEvent(new Event('resize'))      // 直接自定義事件,使用 Event 構造函數:  var event = new Event('build');  var elem = document.querySelector('#id')  // 監聽事件  elem.addEventListener('build', function (e) { ... }, false);  // 觸發事件.  elem.dispatchEvent(event);

 

CustomEvent 可以創建一個更高度自定義事件,還可以附帶一些數據,具體用法如下:
 

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

 

其中 detail 可以存放一些初始化的信息,可以在觸發的時候調用。其他屬性就是定義該事件是否具有冒泡等等功能。
 

內置的事件會由瀏覽器根據某些操作進行觸發,自定義的事件就需要人工觸發。 dispatchEvent 函數就是用來觸發某個事件:
 

  element.dispatchEvent(customEvent);  上面代碼表示,在 element 上面觸發 customEvent 這個事件。    // 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);

 

使用自定義事件需要注意兼容性問題,而使用 jQuery 就簡單多了:

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

 

16.如何從元素中移除事件監聽器 ?
 

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

 

17.如何獲得給定毫秒數的可讀格式 ?
 

  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'

 

18.如何獲得兩個日期之間的差異 (以天為單位) ?
 

  const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>   (dateFinal - dateInitial) / (1000 * 3600 * 24);    // 事例  getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9

 

19.如何向傳遞的URL發出GET請求 ?
 

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

 

20. 如何對傳遞的URL發出POST請求 ?
 

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

 

21.如何為指定選擇器創建具有指定範圍,步長和持續時間的計數器 ?
 

  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”`的元素創建一個2秒計時器

 

22.如何將字符串複製到剪貼板 ?
 

  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

 

23.如何確定頁面的瀏覽器選項卡是否聚焦 ?
 

  const isBrowserTabFocused = () => !document.hidden;    // 事例  isBrowserTabFocused(); // true

 

24. 如何創建目錄 (如果不存在) ?
 

  const fs = require('fs');  const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);    // 事例  createDirIfNotExists('test');

 

這裡面的方法都挺實用的,可以解決很多開發過程問題,大家就好好利用起來吧 !


[lousu-xi ] 24個ES6方法解決JS實際開發問題(小結)已經有255次圍觀

http://coctec.com/docs/javascript/show-post-238202.html