likes
comments
collection
share

5 个 JavaScript “罕见”原生的 API

作者站长头像
站长
· 阅读数 24

本篇带来 5 个 “罕见的” JavaScriot 原生 API,谁还不是个 API 调用大师呢?🐶

闲言少叙,开冲~~

window.getComputedStyle()

window.getComputedStyle()方法返回一个 CSSStyleDeclaration 对象,与 style 属性的类型相同,其中包含元素的计算样式;

用法如下:

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>

getBoundingClientRect()

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

用法如下:

domRect = element.getBoundingClientRect();

返回元素的 left, top, right, bottom, x, y, width, and height 值;

5 个 JavaScript “罕见”原生的 API 比如说要获得 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;

once: true

once: true 可不是 API,它长得也不像 API,它是用来做属性配置的,有了它,再也不用 lodash 的once 了;

const container = document.querySelector<HTMLDivElement>('.container');

container?.addEventListener('click', () => {
  console.log('I will only do it once !')
}, {
  // 配置 once 后,最多调用一次
  once: true
})

哇!原来 JS 就一直自带,你知道吗?

clipboard.readText()

粘贴板,想必是常见要用功能吧~

要从剪贴板读取文本,调用 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);
  }
}

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 = "大写锁定激活: " + x;
    }
</script>

OK,以上就是本篇分享,你“学废”了吗?