Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities
preface
Normal business development, repeat the wheel, repeat the function is always written over and over again, give you a little laugh method, let you develop more relaxed!
1. Determine whether the current TAB is in view/focus
We can use the document.hidden property to check if the current TAB is in view/focus.
const isBrowserTabInView = () = > document.hidden;
isBrowserTabInView(); // true- the current page TAB is hidden, false is currently on the page
Copy the code
2. Check whether the element is currently in focus
We can use the Document.ActiveElement property to check whether the element is currently in focus.
- Document. activeElement points to Document. body;
- During document loading, document.ActiveElement points to null.
const elementIsInFocus = (el) = > (el === document.activeElement);
elementIsInFocus(document.getElementById('id')) // true- in focus, false- not in focus
Copy the code
3. Check whether the current user is on an Apple device
We can use navigator. Platform to check if the current user is on an Apple device.
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
Copy the code
Scroll to the top of the page
The window.scrollto () method scrolls to using x and y coordinates. If you set them to zero and zero, they scroll to the top of the page. Note: Internet Explorer does not support this.scrollto () method.
const goToTop = () = > window.scrollTo(0.0); goToTop();
Copy the code
5. Date formatting — this is a sure thing for front-end development (you can also use the moment.js library)
/ * * *@param {string} format- Format type *@param {number} timestamp- Timestamp *@return {string} * /
function formatDate(format='Y-M-D h:m', timestamp=Date.now()){
let date = new Date(timestamp)
let dateInfo = {
Y: date.getFullYear(),
M: date.getMonth()+1.D: date.getDate(),
h: date.getHours(),
m: date.getMinutes(),
s: date.getSeconds()
}
let formatNumber = (n) = > n > 10 ? n : '0' + n
let res = format
.replace('Y', dateInfo.Y)
.replace('M', dateInfo.M)
.replace('D', dateInfo.D)
.replace('h', formatNumber(dateInfo.h))
.replace('m', formatNumber(dateInfo.m))
.replace('s', formatNumber(dateInfo.s))
return res
}
Copy the code
To predict
formatDate() / / '2021-9-27 14:48'
formatDate(M D D h: M) // 'Sep 27 14:48'
formatDate('h:m Y-M-D'.1582526221604) / / 'let the 2020-2-24'
Copy the code
In actual combat
5. Direct copy without any structure content
copyShaneUrl(shareLink: string) {
const input = document.createElement('input') // Build directly
input input.value = shareLink // Set the content
document.body.appendChild(input) // Add a temporary instance
input.select() // Select the instance content
document.execCommand('Copy') // Perform replication
document.body.removeChild(input) // Delete the temporary instance
}
Copy the code