5

JS小知识,分享五个不常用但又很重要的原生API

 8 months ago
source link: https://www.51cto.com/article/776951.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JS小知识,分享五个不常用但又很重要的原生API

作者:前端达人 2023-12-19 13:30:00
今天给大家分享5个不常用但又很重要的 JavaScript 原生API,熟悉了这些,将会为我们的前端开发带来意想不到的便利。
64a928c67b86c32af7f5462060187f254d638d.png

getBoundingClientRect()

getBoundingClientRect()是JavaScript中的一个函数,它返回一个 DOMRect 矩形对象,该对象表示元素在视口中的位置。这个矩形对象包含了元素的左,上,右和下边界,以及宽度和高度。

domRect = element.getBoundingClientRect();
99b6af35431d0dcd9036158f9ae47afa0f2cec.webp

注意:getBoundingClientRect()是基于视口的,所以坐标是相对于当前视口的。一些浏览器的实现会四舍五入返回的数值,如果精确度要求高可以使用Math.round()解决。

例如,获取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;

window.getComputedStyle()

window.getComputedStyle()是JavaScript中的一个函数,它可以获取一个元素的计算后的样式。返回的是一个CSSStyleDeclaration对象,可以使用它来读取元素的样式信息。

document.defaultView.getComputedStyle(element, [pseudo-element])
//或
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>

once: true

once: true 不是 API,看起来也不像。用于属性配置,有了它,lodash的once就不用了。

"once: true" 是一种 JavaScript 中的事件监听器选项。

当在元素上绑定事件监听器时,可以为其传递一些配置选项。其中之一就是 "once: true",它表示这个事件监听器只会触发一次,之后就会被自动移除。

这种方式可以避免在后续操作中重复触发已经不需要的事件监听器。

举个例子:

const button = document.querySelector('button');
button.addEventListener('click', handleClick, { once: true });

function handleClick(event) {
  console.log('Button was clicked.');
}

第一次点击按钮时,会在控制台中打印 "Button was clicked.",之后再点击按钮将不会有任何反应。

这个特性是在 DOM4 规范中引入的,并在现代浏览器中被广泛支持。

注意:在使用这种方式时,需要注意的是,一旦事件监听器被移除,就不能再次触发。如果需要多次触发,就需要重新绑定事件监听器。

getModifierState()

JavaScript 中的 getModifierState() 方法可用于检查特定的修饰键(如 Alt、Ctrl、CapsLock 或 Shift)是否当前被按下。它是 Event 对象的一个方法。

示例代码:

<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>

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

今天的分享就到这里,希望对你有所帮助。

责任编辑:姜华 来源: 今日头条

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK