本文帶來5個(gè)難得一見的JavaScriot原生API,為我們的前端開發(fā)帶來意想不到的便利。

1. getBoundingClientRect()
Element.getBoundingClientRect() 方法返回一個(gè) DOMRect 對象,該對象提供有關(guān)元素大小及其相對于視口的位置的信息。
domRect = element.getBoundingClientRect();
返回左、上、右、下、x、y、寬度和高度元素的值。

例如,獲取DOM元素相對于頁面左上角的top和left定位距離的值。
const h3 = document.querySelector("h3");
const rect = h3.getBoundingClientRect();
const topElement = document.documentElement;
const positionTop = topElement.scrollTop + rect.top;
const positionLeft = topElement.scrollLeft + rect.left;
2. window.getComputedStyle()
window.getComputedStyle() 方法返回一個(gè) CSSStyleDeclaration 對象,其類型與樣式屬性相同,其中包含元素的計(jì)算樣式。
document.defaultView.getComputedStyle(element, [pseudo-element])
// or
window.getComputedStyle(element, [pseudo-element])
它有兩個(gè)參數(shù),第一個(gè)是計(jì)算樣式的元素,第二個(gè)是偽元素;如果偽元素不存在,則傳遞 null。
例子:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#root {
background-color: pink;
width: 100px;
height: 200px;
}
#root::after {
content: 'Haskell';
display: table;
clear: both;
}
</style>
</head>
<body>
<div id="root" style="background-color: rgb(135, 206, 235);"></div>
</body>
<script>
function getStyleByAttr(node, name) {
return window.getComputedStyle(node, null)[name]
}
const node = document.getElementById('root')
// rgb(135, 206, 235)
console.log(getStyleByAttr(node, 'backgroundColor'))
// 100px
console.log(getStyleByAttr(node, 'width'))
// 200px
console.log(getStyleByAttr(node, 'height'))
// table
console.log(window.getComputedStyle(node, '::after').display)
// Haskell
console.log(window.getComputedStyle(node, '::after').content)
</script>
</html>
3. once: true
once: true 不是 API,看起來也不像。用于屬性配置,有了它,lodash的once就不用了。
const container = document.querySelector<HTMLDivElement>('.container');
container?.addEventListener('click', () => {
console.log('I will only do it once !')
}, {
// After configuring once, it will be called at most once
once: true
})
4. getModifierState()
如果指定的修改鍵被按下或激活,則 getModifierState() 方法返回 true。
例如,我們可以使用它來監(jiān)聽用戶在打字時(shí)是否按下了尺寸切換鍵,然后根據(jù)情況給出適當(dāng)?shù)奶崾尽?/p>
<input type="text" size="40" onkeydown="myFunction(event)">
<p id="demo"></p>
<script>
function myFunction(event) {
var x = event.getModifierState("CapsLock");
document.getElementById("demo").innerHTML = "Caps Lock: " + x;
}
</script>
5.clipboard.readText()
clipboard,我敢肯定,是一個(gè)常用的功能。
要從剪貼板中讀取文本,請調(diào)用 navigator.clipboard.readText() 并等待返回的 Promise 進(jìn)行解析。
async function getClipboardContents() {
try {
const text = await navigator.clipboard.readText();
console.log('Pasted content: ', text);
} catch (err) {
console.error('Failed to read clipboard contents: ', err);
}
}
要將文本復(fù)制到剪貼板,只需調(diào)用 writeText()。
async function copyPageUrl() {
try {
await navigator.clipboard.writeText(location.href);
console.log('Page URL copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
總結(jié)
以上就是我今天想與你分享的5個(gè)關(guān)于JavaScript原生的API的知識內(nèi)容,希望這些內(nèi)容對你有所幫助。