Like and watch. Make it a habit
In this paper,
GitHub
Github.com/qq449245884…Has been included, more past the classification of the highly praised articles, also collated a lot of my documentation, and tutorial materials. Welcome to Star and perfect, you can refer to the interview test point review, I hope we have something together.
This article mainly introduces 24 ES6 methods, these methods are very practical, this book please remember, from time to time to look at.
1. How to hide all specified elements
const hide = (el) => Array.from(el).forEach(e => (e.style.display = 'none')); // Example: Hide all '<img>' elements on the page? hide(document.querySelectorAll('img'))
Copy the code
2. How do I check whether an element has a specified class?
Each node in the DOM of the page has a classList object that allows the programmer to add, delete, and modify CSS classes on the node. Using classList, programmers can also use it to determine whether a node has been assigned a CSS class.
Const hasClass = (el, className) => el.classList.contains(className)'p.special'), 'special') / /true
Copy the code
3. How to switch the class of an element?
const toggleClass = (el, Toggle (className) => el.classList.toggle(className) => el.classList.toggle(className)'p.special'), 'special')
Copy the code
4. How do I obtain the scroll position of the current page?
const getScrollPosition = (el = window) => ({ x: el.pageXOffset ! == undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset ! == undefined ? el.pageYOffset : el.scrollTop }); / / examples/getScrollPosition (); // {x: 0, y: 200}Copy the code
5. How to smoothly scroll to the top of the page
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if(c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); }} // example scrollToTop()Copy the code
Tell the browser window. RequestAnimationFrame () – you want to perform an animation, and required the browser until the next redraw calls the specified callback function to update the animation. This method needs to be passed a callback function as an argument, which will be executed before the browser next redraw.
RequestAnimationFrame: Advantage: The system decides when to execute the callback function. With a refresh frequency of 60Hz, a callback function will be executed during each refresh interval, which will not cause frame loss or lag.
6. How do I check whether a parent element contains children?
const elementContains = (parent, child) => parent ! == child && parent.contains(child); / / examples/elementContains (document. QuerySelector ('head'), document.querySelector('title'));
// true
elementContains(document.querySelector('body'), document.querySelector('body'));
// false
Copy the code
7. How do I check whether the specified element is visible in the viewport?
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
returnpartiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; / / examples/elementIsVisibleInViewport (el); / / need visible elementIsVisibleInViewport (el,true); // Full screen (top, bottom, left, right) is requiredCopy the code
8. How to get all images in an element?
const getImages = (el, includeDuplicates = false) => {
const images = [...el.getElementsByTagName('img')].map(img => img.getAttribute('src'));
returnincludeDuplicates ? images : [...new Set(images)]; }; // Example: includeDuplicates astrueSo we need to exclude repeating elements. GetImages (document,true); / / /'image1.jpg'.'image2.png'.'image1.png'.'... ']
getImages(document, false); / / /'image1.jpg'.'image2.png'.'... ']
Copy the code
9. How do I determine if the device is mobile or desktop/laptop?
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop'; / / examples/detectDeviceType (); //"Mobile" or "Desktop"
Copy the code
10.How to get the current URL?
Const currentURL = () => window.location.href // example currentURL() //'https://google.com'
Copy the code
11. How do I create an object that contains the current URL parameter?
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {} ); / / examples/getURLParameters ('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); / / {}Copy the code
12. How do I convert a set of form elements into objects?
const formToObject = form => Array.from(new FormData(form)).reduce( (acc, [key, value]) => ({ ... acc, [key]: value }), {} ); / / examples/formToObject (document. QuerySelector ('#form'));
// { email: '[email protected]', name: 'Test Name' }
Copy the code
13. How do I retrieve a set of properties indicated by a given selector from an object?
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']
Copy the code
14. How to call the provided function after waiting a specified time?
const delay = (fn, wait. args) =>setTimeout(fn, wait. args); delay(function(text) {
console.log(text);
},
1000,
'later'); // Print after 1 second'later'
Copy the code
15. How to fire a specific event on a given element and optionally pass custom data?
const triggerEvent = (el, eventType, detail) => el.dispatchEvent(new CustomEvent(eventType, { detail })); / / examples/triggerEvent (document. GetElementById ('myId'), 'click');
triggerEvent(document.getElementById('myId'), 'click', { username: 'bob' });
Copy the code
The functions for custom events are Event, CustomEvent, and dispatchEvent
Window.dispatchevent (new Event)'resize')) // Customize the Event directly, using the Event constructor: var Event = new Event('build');
var elem = document.querySelector('#id'// Listen for events elem.addeventListener ()'build'.function (e) { ... }, false); Elem. DispatchEvent (event);Copy the code
CustomEvent can create a more highly customized event with some data attached, as follows:
var myEvent = new CustomEvent(eventname, options); Options can be: {detail: {... }, bubbles:true, // whether bubble cancelable:false// Cancel the default event}Copy the code
The detail can hold some initialization information, and it can be called when it’s fired. The other properties are to define whether the event has bubbling and so on.
Built-in events are triggered by the browser based on certain actions, and custom events need to be triggered manually. The dispatchEvent function is used to trigger an event:
element.dispatchEvent(customEvent);
Copy the code
The above code means that the event customEvent is triggered on the element.
// 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); // Bind the custom event $(element).on(element).'myCustomEvent'.function() {}); $(element).trigger()'myCustomEvent'); // In addition, you can also pass more parameter information when triggering custom events: $("p" ).on( "myCustomEvent".function( event, myName ) {
$( this ).text( myName + ", hi there!" );
});
$( "button" ).click(function() {$("p" ).trigger( "myCustomEvent"["John"]); });Copy the code
16. How to remove an event listener from an element?
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);
Copy the code
17. How do I get a readable format for a given number of milliseconds?
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
};
returnObject.entries(time) .filter(val => val[1] ! == 0) .map(([key, val]) => `${val} ${key}${val ! = = 1? 's' : ''}`)
.join(', '); }; / / examples/formatDuration (1001); //'1 second, 1 millisecond'
formatDuration(34325055574);
// '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
Copy the code
18. How do I get the difference between two dates (in days)?
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); // example getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); / / 9Copy the code
19. How do I send a GET request to the passed URL?
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"}
Copy the code
20. How do I send a POST request to the URL that was passed?
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"}
Copy the code
21. How to create a counter with a specified range, step, and duration for a specified selector?
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))));
returntimer; }; / / examples/counter ('#my-id', 1, 1000, 5, 2000); // Let 'id=' my-id ' 'element create a 2 second timerCopy the code
22. How do I copy strings to the clipboard?
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); }}; // example copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboardCopy the code
23. How do I determine if the browser TAB of a page is focused?
const isBrowserTabFocused = () => ! document.hidden; / / examples/isBrowserTabFocused (); //true
Copy the code
24. How do I create a directory if it does not exist?
const fs = require('fs'); const createDirIfNotExists = dir => (! fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined); / / examples/createDirIfNotExists ('test');
Copy the code
Most of these methods are very practical and can solve many development process problems, so let’s make good use of them.
The possible bugs after the deployment of code can not be known in real time, in order to solve these bugs, spent a lot of time log debugging, here by the way to recommend you a good BUG monitoring toolFundebug.
Dev. To/madarsbiss /…
By Madza
communication
The article is updated every week. You can search “Big Move World” on wechat for the first time to read and hurry up (one or two articles earlier than the blog yo). This article is GitHub github.com/qq449245884… Welcome to Star and improve. You can refer to the exam site for review during the interview. In addition, you can follow the public account and reply welfare in the background, so that you can see the welfare, you know.