Reprinted fromDo these Web apis really work? Don’t ask. It helps to ask
Smart CSS Development Tips (66 Practical tips, bookmarks)
This article provides a fairly extensive list of less common Web apis, so compatibility is not covered in this article and you can check it out for yourself. The following cases can be matched with the GIF I try to match, so as not to content dry grass boring, but if the content is wrong, please also spray or correct 👌
Methods list
querySelector
(Element queries down, returns one)querySelectorAll
(Element queries down, returns multiple)closest
(Element up query)dataset
Get the element to”data-
“Is the set of attributes prefixed by.URLSearchParams
(Query parameters)hidden
(Hidden elements)contenteditable
(Make elements editable)spellCheck
(Check pinyin)classList
(Class name Controller)getBoundingClientRect
(Element spatial structure details)contains
(Check whether the specified element is included)online state
(Network status)battery state
(Battery status)vibration
(Equipment vibration)page visibility
(Page visibility)deviceOrientation
(Gyroscope)toDataUrl
(Canvas content turnbase64
)customEvent
(Custom events)notification
(Desktop Notification)fullScreen
(full screen)orientation
(Screen orientation)
Then built
1. querySelector
GetElementById is still used in 9102 years 😭
Gets the element from the specified element that matches the CSS selector:
Document document.querySelector("#nav"); // Get id= in the file"nav"The element of the document. QuerySelector (".nav"); // Get the class= in the document"nav"The element of the document. QuerySelector ("#nav li:first-child"); // Get id= in the file"nav"The first li element down hereCopy the code
// Can also be applied to other elementslet nav = dodocument.querySelector("#nav"); nav.querySelector("li"); // If there are more than one Li, return the first liCopy the code
Note: only one element is returned anyway. If there are more than one element, only the first ✅
2. querySelectorAll
Gets all elements of the specified element that match the CSS selector:
let list = document.querySelectorAll("li"); // NodeList(2) [li, liCopy the codeCopy the code
Note: The value returned is an array of classes. You cannot use the array’s native methods (forEach, map, etc.).
Array.from(list).map();
Copy the codeCopy the code
3. closest
In contrast to querySelector, this element can be queried up, to the parent element:
document.querySelector("li").closest("#nav");
Copy the codeCopy the code
4. dataset
Just like the native wechat applet, it can get the set of attributes prefixed with “data-” on the tag:
<p data-name="Spider-man" data-age="16"></p>
Copy the codeCopy the code
document.querySelector("p").dataset; // {name: "Spider-man", age: "16"}
Copy the codeCopy the code
Note: the getAttribute method can be used to obtain any attribute value, but the properties are different. This is a development specification problem. All custom attributes must be prefixed with data- ✅
5. URLSearchParams
Suppose the browser url parameter is “? Name = spiderman &age=16”
new URLSearchParams(location.search).get("name"); / / spider-manCopy the codeCopy the code
6. hidden
This is an HTML attribute that specifies whether or not the element is hidden and behaves like CSS display: None:
<div hidden> I am hidden </div>Copy the codeCopy the code
document.querySelector("div").hidden = true / false;
Copy the codeCopy the code
7. contenteditable
An element can be made editable by the user:
<p contenteditable> I am a P element, but I can also be edited </p>Copy the codeCopy the code
The effect is as follows:
A fascinating story can be told when this property meets the style tag: contenteditable and user-modify can also be played 🌚
8. spellcheck
Is also an HTML property that specifies whether the input is checked for English spelling:
<! -- Default istrue, can be omitted --> <textarea spellcheck="true"></textarea>
Copy the codeCopy the code
The effect is as follows:
Setting do not check:
<textarea spellcheck="false"></textarea>
Copy the codeCopy the code
The effect is as follows:
9. classList
This is an object that encapsulates a number of methods that operate on element class names:
<p class="title"></p>
Copy the codeCopy the code
let elem = document.querySelector("p");
// Add the class name elem.classlist. add("title-new"); // "title title-new"
Remove ("title"); // Delete the class name elem.classlist. remove("title"); // "title-new"
Elem.classlist. toggle("title"); // Toggle ("title"); // "title-new title"
// Replace the class name elem.classlist. replace("title", "title-old"); // "title-new title-old"
Copy the code
// Contains the specified class name elem.classList.contains("title"); // false Copy the code
10. getBoundingClientRect
You can get spatial information for the specified element on the current page:
elem.getBoundingClientRect(); Copy the code
// return {x: 604.875, y: 1312, width: 701.625, height: 31, top: 1312, right: 136.5, bottom: 1343, left: 604.875}Copy the code
11. contains
We can determine if the specified element contains the specified child elements:
<div>
<p></p>
</div>
Copy the codeCopy the code
document.querySelector("div").contains(document.querySelector("p")); // true
Copy the codeCopy the code
12. online state
Listen for the current network state change and execute the corresponding method:
window.addEventListener("online", xxx); Copy the code
window.addEventListener("offline", () => { alert("You're off the Internet!"); }); Copy the code
The PC effect is as follows:
The mobile terminal effect is as follows:
Usage scenario: prompt the user has broken the network, a box to scare the user directly ✅
13. battery state
Get the battery status of the device:
navigator.getBattery().then(battery => console.log(battery));
// How long is the charging point? // How long is the charging point? // How long is the charging point
Copy the code
Onchargingchange, // Listen for charging status change onChargingTimechange, // Listen for chargingtimechange ondisChargingTimechange, Onlevelchange onLevelchangeCopy the code
Usage scenario: prompt the user power has been full, or in order to let the user have a sense of security, the power is lower than 99% of the time to a pop-up prompt “the charge “✅
14. vibration
Hee hee, make the equipment vibrate:
// Vibrate once navigator. Vibrate (100);Copy the code
Vibrate ([200, 100, 300]); vibrate([200, 100, 300]);Copy the code
Here’s how it works: Sorry you have to hold the phone with your own hand to feel it;
Usage scenario: Provide sensory feedback through vibration, such as continuous vibration to remind users ✅ when they have not touched the screen for too long
15. page visibility
As the name suggests, this API is used to listen for changes in page visibility, which is triggered when the TAB bar switches and minimizes on the PC side, or triggered when the application cuts to the background on the mobile side. Simply put, the page disappears 🤦♂️
document.addEventListener("visibilitychange", () => {console.log(' page visibility:${document.visibilityState}`);
});
Copy the codeCopy the code
The PC effect is as follows:
The mobile terminal effect is as follows:
Usage scenario: when the program is cut to the background, if there is currently a video playing or some animation execution, can first pause ✅
16. deviceOrientation
Gyroscope, also known as device orientation, aka gravity sensing, is a solution to the API failure on IOS devices by changing the domain protocol to HTTPS;
Alpha, beta, and gamma from left to right;
window.addEventListener("deviceorientation", event => { let { alpha, beta, gamma } = event; Copy the code
console.log(
Alpha: < span class = "HLJS - variable" > ${alpha} < / span >
); console.log(Beta: < span class = "HLJS - variable" > ${beta} < / span >
); console.log(Gamma: < span class = "HLJS - variable" > ${gamma} < / span >
); }); Copy the code
The mobile effect is as follows (the phone is constantly turning) :
Usage scenario: Some elements on the page need to move according to the mobile phone swing, to achieve the effect of parallax, such as king of Glory into the game interface, mobile phone rotation background will follow 😂
17. toDataURL
The Canvas API converts the content of the canvas into a base64 image address.
let canvas = document.querySelector("canvas"); let context = canvas.getContext("2d");
// Draw something...
Copy the code
let url = canvas.toDataURL("image/png"); // Convert canvas content to base64 addressCopy the code
When using tag A for image download, the image link is cross-domain (the image is my gold-digging avatar), and the image preview cannot be performed instead:
<img src="xxx">
<button>
<a href="xxx" download="avatar"</a> </button>Copy the codeCopy the code
The effect is as follows:
Wrap the following code to solve ✅
Const downloadImage = (URL, name) => {// Instantiate canvaslet canvas = document.createElement("canvas"); let context = canvas.getContext("2d");
// instantiate an image object let image = new image (); image.crossOrigin = "Anonymous"; image.src = url;
Image.onload = () => {// Draw the image on canvas. Height = image.height; canvas.width = image.width; context.drawImage(image, 0, 0);
<span class="hljs-built_in">let</span> dataURL = canvas.todataurl (<span class="hljs-string">"image/png"</span>); <span class="hljs-built_in">let</span> a = document.createElement(<span) class="hljs-string">"a"</span>); a.hidden = <span class="hljs-literal">true</span>; a.href = dataURL; a.download = name; document.body.appendChild(a); a.click();Copy the code
Copy the code
}}Copy the code
The effect is as follows:
Or convert the current DOM to an image for download, often used to generate a poster: HTML2Canvas
18. customEvent
Custom events, like on and emit in VUE;
Listening for custom events:
window.addEventListener("follow", event => { console.log(event.detail); // 输出 {name: Front-end Space Intelligence.}});Copy the codeCopy the code
Send a defined event:
window.dispatchEvent(new CustomEvent("follow", { detail: { name: Front-end Space Intelligence.}}));Copy the codeCopy the code
19. notification
Desktop notification on PC side, such as wechat on web side, when receiving a message, a notification will appear in the lower right corner (although you minimize the browser), because this notification is independent of the browser, is a native control of the system;
const notice = new Notification(Front-end Space Intelligence., { body: "Are these 20 uncommon Web apis really useful? , don't ask, ask is useful 🈶", icon: "My head of gold nuggets.", data: { url: "https://www.baidu.com"}});Copy the code
// Click the callback notice.onclick = () => {window.open(notice.data.url); // When the user clicks on the notification, open baidu website in the browser}Copy the code
The effect is as follows:
Note: To successfully invoke notifications, the user’s authorization is required ✅
Notification.requestPermission(prem => { prem == "granted"// Agree prem =="denied"/ / reject})Copy the codeCopy the code
So, make a request to the user before calling again:
let permission = Notification.permission; Copy the code
if (permission == "granted") {// Agreed, start sending notifications... }else if (permission == "denied") {// do not agree, can not send}else{/ / other state, can again send authorization prompt Notification. RequestPermission (); }Copy the code
20. fullScreen
Full screen no? In the previous project, this applies not only to the documentElement, but also to the specified element.
/** * @method launchFullScreen * @param {Object} elem = document.documentElement */ const launchFullScreen = (elem = document.documentElement) => {if(elem.requestFullScreen) { elem.requestFullScreen(); } else if(elem.mozRequestFullScreen) { elem.mozRequestFullScreen(); } else if(elem.webkitRequestFullScreen) { elem.webkitRequestFullScreen(); }}Copy the codeCopy the code
The documentElement function is equivalent to F11 turning on full screen:
So what happens to the specified element?
Just like renderings, the full screen is turned on directly, and only the specified elements are shown, whose width and height fill the entire screen ✅
When turning off full screen, note that the document object is always used:
/** * @method exitFullScreen turns off FullScreen */ constexitFullScreen = () => { if (document.exitFullscreen) { document.exitFullscreen(); } else if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); } else if(document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); }}Copy the codeCopy the code
Usage scenario: The user needs to focus on something, such as a full-screen code editing area ✅
21. orientation
Can monitor the user’s mobile phone device rotation direction change;
window.addEventListener("orientationchange", () => {document.body.innerhtml += '<p> The Angle value of the rotated screen:${window.orientation}</p>`; }, false); Copy the codeCopy the code
The effect is as follows:
You can also use CSS media query:
/* @media all and (orientation: portrait) {body::after {content:"Portrait"}}Copy the code
/* @media all and (orientation: landscape) {body::after {content:"Landscape"}}Copy the code
Usage scenario: the page requires users to open the landscape screen to get a better experience, such as the active page 😂 in King of Glory
conclusion
In fact, there are a lot of things that are not commonly used, there are a lot of things that I haven’t found or written, such as geoLocation, execCommand, etc. Welcome to add, the first few articles are related to CSS, the next few articles will not write CSS, for a lot of things we have written, want to write something new, but it is inevitable to conflict
Finally, the public number
That’s the end of this article, I hope you found the above content helpful, please remember to like and follow 💨 if you like
Wechat official account
Front-end Space Intelligence
, will not regularly update the latest practical front-end skills/technical articles, welcome to pay attention to, I will give you more good articles, mutual encouragement! 🌗