In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what are the ES6 methods to solve JS problems". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. How to hide all specified elements:
Const hide = (el) = > Array.from (el) .forEach (e = > (e.style.display = 'none')); / / case: hide all `on the page
`element? Hide (document.querySelectorAll ('img'))
2. How do I check whether an element has a specified class?
There is a classList object on each node in the page DOM, which programmers can use to add, delete, and modify CSS classes on nodes; 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 do I 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);}}
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 to check whether 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 the specified element is visible in the 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?
Const detectDeviceType = () = > / 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 child 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, CustoEvent, 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
19. How do I make an 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"}
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 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);}}; / / 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); / / example createDirIfNotExists ('test'); what are the ES6 methods to solve the JS problem? thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.