5 个罕见的 JavaScript 原生 API

作者: jie 分类: JavaScript 发布时间: 2023-06-08 09:44

本文带来5个难得一见的JavaScriot原生API,为我们的前端开发带来意想不到的便利。

1. getBoundingClientRect()

Element.getBoundingClientRect() 方法返回一个 DOMRect 对象,该对象提供有关元素大小及其相对于视口的位置的信息。

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() 方法返回一个 CSSStyleDeclaration 对象,其类型与样式属性相同,其中包含元素的计算样式。

document.defaultView.getComputedStyle(element, [pseudo-element])
// or
window.getComputedStyle(element, [pseudo-element])

它有两个参数,第一个是计算样式的元素,第二个是伪元素;如果伪元素不存在,则传递 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。

例如,我们可以使用它来监听用户在打字时是否按下了尺寸切换键,然后根据情况给出适当的提示

<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,我敢肯定,是一个常用的功能。

要从剪贴板中读取文本,请调用 navigator.clipboard.readText() 并等待返回的 Promise 进行解析。

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);
  }
}

要将文本复制到剪贴板,只需调用 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);
  }
}

发表回复