Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What ES6 methods can be used to solve the JS problem of actual development?

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "what ES6 methods are used to solve the actual development JS problems". In the daily operation, I believe many people have doubts about what ES6 methods are used to solve the actual development JS problems. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful for you to answer the doubts of "what ES6 methods are used to solve the actual development JS problems"! Next, please follow the editor to study!

1. How to hide all specified elements

Const hide = (... el) = > [... el] .forEach (e = > (e.style.display = 'none')) / / case: hide all `on the page

`element? Hide (document.querySelectorAll ('img'))

two。 How do I check if an element has a specified class?

There is a classList object on each node in the page DOM, and programmers can use the methods to add, delete, and modify CSS classes on the node. Using classList, programmers can also use it to determine whether a node is assigned a CSS class.

Const hasClass = (el, className) = > el.classList.contains (className) / / case hasClass (document.querySelector ('p.special`),' special') / / true

3. How do I switch the classes of an element?

Const toggleClass = (el, className) = > el.classList.toggle (className) / / case removal p special class toggleClass with class `special` (document.querySelector ('p.special`),' special')

4. How do I get the scrolling 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}); / / case getScrollPosition (); / / {x: 0, y: 200}

5. How to scroll smoothly 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);}} / / case scrollToTop ()

Window.requestAnimationFrame () tells the browser that you want to perform an animation and asks the browser to call the specified callback function to update the animation before the next redraw. This method needs to pass in a callback function as an argument, which will be executed before the browser's next redraw.

RequestAnimationFrame: advantage: the timing of the callback function is determined by the system. The refresh rate of 60Hz, then a callback function will be executed in each refresh interval, which will not cause frame loss or stutter.

6. How do I check if the parent element contains child elements?

Const elementContains = (parent, child) = > parent! = child & & parent.contains (child); / / case elementContains (document.querySelector ('head'), document.querySelector (' title')); / / true elementContains (document.querySelector ('body'), document.querySelector (' body')); / / false

7. How do I check whether a specified element is visible in a viewport?

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 img.getAttribute ('src')); return includeDuplicates? Images: [... new Set (images)];}; / / example: if includeDuplicates is true, it means that the repeating element getImages (document, true) needs to be excluded; / / ['image1.jpg',' image2.png', 'image1.png','] GetImages (document, false); / / ['image1.jpg',' image2.png', '...]

9. How do I determine if the device is a mobile device or a desktop / laptop?

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

10.How to get the current URL?

Const currentURL = () = > _ window.location.href / / case currentURL () / / 'https://google.com'

11. How do I create an object that contains the current URL parameters?

Const getURLParameters = url = > (url.match (/ ([^? = &] +) (= ([^ &] *) / g) | | []) .reduce ((a, v) = > (a [v.slice (0, v.indexOf ('='))] = v.slice (v.indexOf ('=') + 1), a), {}); / / case getURLParameters ('http://url.com/page?n=Adam&s=Smith');) / / {n: 'Adam', 's:' Smith'} getURLParameters ('google.com'); / / {}

twelve。 How do I convert a set of form elements to objects?

Const formToObject = form = > Array.from (new FormData (form)). Reduce ((acc, [key, value]) = > ({... acc, [key]: value}), {}); / / case formToObject (document.querySelector ('# form')); / / {email: 'test@email.com', name:' Test Name'}

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: {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. How do I call the provided function after waiting for a specified time?

Const delay = (fn, wait,... args) = > setTimeout (fn, wait,.. ARGs); delay (function (text) {console.log (text);}, 1000, 'later'); / / print' later' after 1 second

15. How can I trigger a specific event on a given element and selectively pass custom data?

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

The functions for custom events are Event, CustomEvent, and dispatchEvent

/ / dispatch a resize built-in event window.dispatchEvent (new Event ('resize')) / / directly customize the event to window, using the Event constructor: var event = new Event (' build'); var elem = document.querySelector ('# id') / / listening event elem.addEventListener ('build', function (e) {...}, false); / / triggering the event. Elem.dispatchEvent (event)

CustomEvent can create a more highly customized event, along with some data, as follows:

Var myEvent = new CustomEvent (eventname, options); where options can be: {detail: {...}, bubbles: true, / / whether to bubble cancelable: false / / whether to cancel the default event}

Detail can store some initialization information, which can be called when it is triggered. 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)

The above code indicates 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); using custom events requires attention to compatibility issues, while using jQuery is much easier: / / bind custom events $(element) .on ('myCustomEvent', function () {}) / / trigger event $(element) .trigger ('myCustomEvent'); / / in addition, you can pass more parameter information when triggering a custom event: $("p"). On ("myCustomEvent", function (event, myName) {$(this). Text (myName + ", hi there!");}) $("button") .click (function () {$("p") .trigger ("myCustomEvent", ["John"]);})

16. How do I remove event listeners 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)

17. How to 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 }; return Object.entries(time) .filter(val =>

Val [1]! = = 0) .map (([key, val]) = > `${val} ${key} ${val! = = 1? 's':'} `) .join (',');}; / / case formatDuration (1001); / /'1 second, 1 millisecond' formatDuration (34325055574); / / '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'

18. How do I get the difference between two dates (in days)?

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

K45K G21G

20. How do I make a POST request to the passed URL?

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. How do I create a counter with a specified range, step size, 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) [xss_clean] = current; if (current > = end) document.querySelector (selector) [xss_clean] = end; if (current > = end) clearInterval (timer);}, Math.abs (Math.floor (duration / (end-start); return timer;}; / / case counter ('# my-id', 1, 1000, 5, 2000) / / Let the element of `id= "my-id" `create a 2-second timer

twenty-two。 How do I copy a string to the clipboard?

Const copyToClipboard = str = > {const el = document.createElement ('textarea'); el.value = str; el.setAttribute (' readonly',''); el.style.position = 'absolute'; el.style.left ='-9999pxrabbit; 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);}}; / / case copyToClipboard (' Lorem ipsum'); / / 'Lorem ipsum' copied to clipboard

23. How do I determine if the browser tab of the page is focused?

Const isBrowserTabFocused = () = >! document.hidden; / / case isBrowserTabFocused (); / / true

24. How do I create a directory if it doesn't exist?

Const fs = require ('fs'); const createDirIfNotExists = dir = > (! fs.existsSync (dir)? Fs.mkdirSync (dir): undefined); / / case createDirIfNotExists ('test'); at this point, the study on "what ES6 methods are available to solve the JS problems actually developed" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report