记好这24个ES6方法,用于解决实际开发的JS问题
2021-04-10 15:26
window.requestAnimationFrame()
告诉浏览器-你希望执行一个动画,并且要求浏览器在下一重绘之前调用指定的函数更新动画。之前执行。
requestAnimationFrame
:优势:由系统决定决定功能的执行时机。60Hz的刷新频率,然后每次刷新的间隔中会执行一次替换函数,不会引起丢帧,不会卡顿。
6.如何检查父元素是否包含子元素?
1 const elementContains = (parent, child) => parent !== child && parent.contains(child); 2 3 // 事例 4 elementContains(document.querySelector(‘head‘), document.querySelector(‘title‘)); 5 // true 6 elementContains(document.querySelector(‘body‘), document.querySelector(‘body‘)); 7 // false
7.如何检查指定的元素在视口中是否可见?
1 const elementIsVisibleInViewport = (el, partiallyVisible = false) => { 2 const { top, left, bottom, right } = el.getBoundingClientRect(); 3 const { innerHeight, innerWidth } = window; 4 return partiallyVisible 5 ? ((top > 0 && top 0 && bottom 6 ((left > 0 && left 0 && right innerWidth)) 7 : top >= 0 && left >= 0 && bottom innerWidth; 8 }; 9 10 // 事例 11 elementIsVisibleInViewport(el); // 需要左右可见 12 elementIsVisibleInViewport(el, true); // 需要全屏(上下左右)可以见
8.如何获取元素中的所有图像?
1 const getImages = (el, includeDuplicates = false) => { 2 const images = [...el.getElementsByTagName(‘img‘)].map(img => img.getAttribute(‘src‘)); 3 return includeDuplicates ? images : [...new Set(images)]; 4 }; 5 6 // 事例:includeDuplicates 为 true 表示需要排除重复元素 7 getImages(document, true); // [‘image1.jpg‘, ‘image2.png‘, ‘image1.png‘, ‘...‘] 8 getImages(document, false); // [‘image1.jpg‘, ‘image2.png‘, ‘...‘]
9.如何确定设备是移动设备还是台式机/笔记本电脑?
1 const detectDeviceType = () => 2 /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) 3 ? ‘Mobile‘ 4 : ‘Desktop‘; 5 6 // 事例 7 detectDeviceType(); // "Mobile" or "Desktop"
10.如何获取当前URL?
1 const currentURL = () => window.location.href 2 3 // 事例 4 currentURL() // ‘https://google.com‘
11.如何创建一个包含当前URL参数的对象?
1 const getURLParameters = url => 2 (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( 3 (a, v) => ((a[v.slice(0, v.indexOf(‘=‘))] = v.slice(v.indexOf(‘=‘) + 1)), a), 4 {} 5 ); 6 7 // 事例 8 getURLParameters(‘http://url.com/page?n=Adam&s=Smith‘); // {n: ‘Adam‘, s: ‘Smith‘} 9 getURLParameters(‘google.com‘); // {}
12.如何将一组表单元素转化为对象?
1 const formToObject = form => 2 Array.from(new FormData(form)).reduce( 3 (acc, [key, value]) => ({ 4 ...acc, 5 [key]: value 6 }), 7 {} 8 ); 9 10 // 事例 11 formToObject(document.querySelector(‘#form‘)); 12 // { email: ‘test@email.com‘, name: ‘Test Name‘ }
13.如何从对象检索给定选择器指示的一组属性?
1 const get = (from, ...selectors) => 2 [...selectors].map(s => 3 s 4 .replace(/\[([^\[\]]*)\]/g, ‘.$1.‘) 5 .split(‘.‘) 6 .filter(t => t !== ‘‘) 7 .reduce((prev, cur) => prev && prev[cur], from) 8 ); 9 const obj = { selector: { to: { val: ‘val to select‘ } }, target: [1, 2, { a: ‘test‘ }] }; 10 11 // Example 12 get(obj, ‘selector.to.val‘, ‘target[0]‘, ‘target[2].a‘); 13 // [‘val to select‘, 1, ‘test‘]
14.如何在等待指定时间后调用提供的函数?
1 const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); 2 delay( 3 function(text) { 4 console.log(text); 5 }, 6 1000, 7 ‘later‘ 8 ); 9 10 // 1秒后打印 ‘later‘
15.如何在给定元素上触发特定事件且能选择地传递自定义数据?
1 const triggerEvent = (el, eventType, detail) => 2 el.dispatchEvent(new CustomEvent(eventType, { detail })); 3 4 // 事例 5 triggerEvent(document.getElementById(‘myId‘), ‘click‘); 6 triggerEvent(document.getElementById(‘myId‘), ‘click‘, { username: ‘bob‘ });
自定义事件的函数有Event
,CustomEvent
和dispatchEvent
1 // 向 window派发一个resize内置事件 2 window.dispatchEvent(new Event(‘resize‘)) 3 4 5 // 直接自定义事件,使用 Event 构造函数: 6 var event = new Event(‘build‘); 7 var elem = document.querySelector(‘#id‘) 8 // 监听事件 9 elem.addEventListener(‘build‘, function (e) { ... }, false); 10 // 触发事件. 11 elem.dispatchEvent(event);
CustomEvent
可以创建一个更高度自定义事件,还可以附带一些数据,具体用法如下:
1 var myEvent = new CustomEvent(eventname, options); 2 其中 options 可以是: 3 { 4 detail: { 5 ... 6 }, 7 bubbles: true, //是否冒泡 8 cancelable: false //是否取消默认事件 9 }
其中detail
可以存放一些初始化的信息,可以在触发的时候调用。其他属性就是定义该事件是否具有冒泡等等功能。
。内置的事件会由浏览器根据某些操作进行触发,定义自事件的就需要人工触发 dispatchEvent
函数就是用来触发某个事件:
1 element.dispatchEvent(customEvent);
上面的代码表示,在element
上面触发customEvent
这个事件。
1 // add an appropriate event listener 2 obj.addEventListener("cat", function(e) { process(e.detail) }); 3 4 // create and dispatch the event 5 var event = new CustomEvent("cat", {"detail":{"hazcheeseburger":true}}); 6 obj.dispatchEvent(event); 7 使用自定义事件需要注意兼容性问题,而使用 jQuery 就简单多了: 8 9 // 绑定自定义事件 10 $(element).on(‘myCustomEvent‘, function(){}); 11 12 // 触发事件 13 $(element).trigger(‘myCustomEvent‘); 14 // 此外,你还可以在触发自定义事件时传递更多参数信息: 15 16 $( "p" ).on( "myCustomEvent", function( event, myName ) { 17 $( this ).text( myName + ", hi there!" ); 18 }); 19 $( "button" ).click(function () { 20 $( "p" ).trigger( "myCustomEvent", [ "John" ] ); 21 });
16.如何从元素中移除事件监听器?
1 const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); 2 3 const fn = () => console.log(‘!‘); 4 document.body.addEventListener(‘click‘, fn); 5 off(document.body, ‘click‘, fn);
17.如何获得给定毫秒数的扩展格式?
1 const formatDuration = ms => { 2 if (ms ms; 3 const time = { 4 day: Math.floor(ms / 86400000), 5 hour: Math.floor(ms / 3600000) % 24, 6 minute: Math.floor(ms / 60000) % 60, 7 second: Math.floor(ms / 1000) % 60, 8 millisecond: Math.floor(ms) % 1000 9 }; 10 return Object.entries(time) 11 .filter(val => val[1] !== 0) 12 .map(([key, val]) => `${val} ${key}${val !== 1 ? ‘s‘ : ‘‘}`) 13 .join(‘, ‘); 14 }; 15 16 // 事例 17 formatDuration(1001); // ‘1 second, 1 millisecond‘ 18 formatDuration(34325055574); 19 // ‘397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds‘
18.如何获得两个日期之间的差异(以天为单位)?
1 const getDaysDiffBetweenDates = (dateInitial, dateFinal) => 2 (dateFinal - dateInitial) / (1000 * 3600 * 24); 3 4 // 事例 5 getDaysDiffBetweenDates(new Date(‘2017-12-13‘), new Date(‘2017-12-22‘)); // 9
19.如何向后传递的URL发出GET请求?
1 const httpGet = (url, callback, err = console.error) => { 2 const request = new XMLHttpRequest(); 3 request.open(‘GET‘, url, true); 4 request.onload = () => callback(request.responseText); 5 request.onerror = () => err(request); 6 request.send(); 7 }; 8 9 httpGet( 10 ‘https://jsonplaceholder.typicode.com/posts/1‘, 11 console.log 12 ); 13 14 // {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}
20.如何对传递的URL发出POST请求?
1 const httpPost = (url, data, callback, err = console.error) => { 2 const request = new XMLHttpRequest(); 3 request.open(‘POST‘, url, true); 4 request.setRequestHeader(‘Content-type‘, ‘application/json; charset=utf-8‘); 5 request.onload = () => callback(request.responseText); 6 request.onerror = () => err(request); 7 request.send(data); 8 }; 9 10 const newPost = { 11 userId: 1, 12 id: 1337, 13 title: ‘Foo‘, 14 body: ‘bar bar bar‘ 15 }; 16 const data = JSON.stringify(newPost); 17 httpPost( 18 ‘https://jsonplaceholder.typicode.com/posts‘, 19 data, 20 console.log 21 ); 22 23 // {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}
21.如何为指定选择器创建具有指定范围,步长和持续时间的计数器?
1 const counter = (selector, start, end, step = 1, duration = 2000) => { 2 let current = start, 3 _step = (end - start) * step step : step, 4 timer = setInterval(() => { 5 current += _step; 6 document.querySelector(selector).innerHTML = current; 7 if (current >= end) document.querySelector(selector).innerHTML = end; 8 if (current >= end) clearInterval(timer); 9 }, Math.abs(Math.floor(duration / (end - start)))); 10 return timer; 11 }; 12 13 // 事例 14 counter(‘#my-id‘, 1, 1000, 5, 2000); 15 // 让 `id=“my-id”`的元素创建一个2秒计时器
22.如何将字符串复制到顶点?
1 const el = document.createElement(‘textarea‘); 2 el.value = str; 3 el.setAttribute(‘readonly‘, ‘‘); 4 el.style.position = ‘absolute‘; 5 el.style.left = ‘-9999px‘; 6 document.body.appendChild(el); 7 const selected = 8 document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; 9 el.select(); 10 document.execCommand(‘copy‘); 11 document.body.removeChild(el); 12 if (selected) { 13 document.getSelection().removeAllRanges(); 14 document.getSelection().addRange(selected); 15 } 16 }; 17 18 // 事例 19 copyToClipboard(‘Lorem ipsum‘); 20 // ‘Lorem ipsum‘ copied to clipboard
23.如何确定页面的浏览器选项卡是否聚焦?
1 const isBrowserTabFocused = () => !document.hidden; 2 3 // 事例 4 isBrowserTabFocused(); // true
24.如何创建目录(如果不存在)?
1 const fs = require(‘fs‘); 2 const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined); 3 4 // 事例 5 createDirIfNotExists(‘test‘);
这里面的方法大都挺实用,可以解决很多开发过程问题,大家就好好利用起来吧。
原文地址:https://juejin.im/post/5e5ef2f9f265da57685dc9c1
本文章仅做学习记录,侵删
上一篇:PHP页面中文乱码处理办法
下一篇:JS 函数柯里化
文章标题:记好这24个ES6方法,用于解决实际开发的JS问题
文章链接:http://soscw.com/index.php/essay/73848.html