JS小知识,分享五个不常用但又很重要的原生API
2023-12-19 09:35:16 软件 240观看
摘要getBoundingClientRect()getBoundingClientRect()是JavaScript中的一个函数,它返回一个 DOMRect 矩形对象,该对象表示元素在视口中的位置。这个矩形对象包含了元素的左,上,右和下边界,以及宽度和高度。domRect = element.g

KdG28资讯网——每日最新资讯28at.com

getBoundingClientRect()

getBoundingClientRect()是JavaScript中的一个函数,它返回一个 DOMRect 矩形对象,该对象表示元素在视口中的位置。这个矩形对象包含了元素的左,上,右和下边界,以及宽度和高度。KdG28资讯网——每日最新资讯28at.com

domRect = element.getBoundingClientRect();

KdG28资讯网——每日最新资讯28at.com

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

例如,获取DOM元素相对于页面左上角的top和left定位距离的值。KdG28资讯网——每日最新资讯28at.com

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对象,可以使用它来读取元素的样式信息。KdG28资讯网——每日最新资讯28at.com

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

它有两个参数,第一个是计算样式的元素,第二个是伪元素;如果伪元素不存在,则传递 null。KdG28资讯网——每日最新资讯28at.com

<!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就不用了。KdG28资讯网——每日最新资讯28at.com

"once: true" 是一种 JavaScript 中的事件监听器选项。KdG28资讯网——每日最新资讯28at.com

当在元素上绑定事件监听器时,可以为其传递一些配置选项。其中之一就是 "once: true",它表示这个事件监听器只会触发一次,之后就会被自动移除。KdG28资讯网——每日最新资讯28at.com

这种方式可以避免在后续操作中重复触发已经不需要的事件监听器。KdG28资讯网——每日最新资讯28at.com

举个例子:KdG28资讯网——每日最新资讯28at.com

const button = document.querySelector('button');button.addEventListener('click', handleClick, { once: true });function handleClick(event) {  console.log('Button was clicked.');}

第一次点击按钮时,会在控制台中打印 "Button was clicked.",之后再点击按钮将不会有任何反应。KdG28资讯网——每日最新资讯28at.com

这个特性是在 DOM4 规范中引入的,并在现代浏览器中被广泛支持。KdG28资讯网——每日最新资讯28at.com

注意:在使用这种方式时,需要注意的是,一旦事件监听器被移除,就不能再次触发。如果需要多次触发,就需要重新绑定事件监听器。KdG28资讯网——每日最新资讯28at.com

getModifierState()

JavaScript 中的 getModifierState() 方法可用于检查特定的修饰键(如 Alt、Ctrl、CapsLock 或 Shift)是否当前被按下。它是 Event 对象的一个方法。KdG28资讯网——每日最新资讯28at.com

示例代码:KdG28资讯网——每日最新资讯28at.com

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

剪贴板,我敢肯定,是一个常用的功能。KdG28资讯网——每日最新资讯28at.com

要从剪贴板中读取文本,请调用navigator.clipboard.readText() 并等待返回的 Promise 进行解析。KdG28资讯网——每日最新资讯28at.com

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()。KdG28资讯网——每日最新资讯28at.com

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

结束语

今天的分享就到这里,希望对你有所帮助。KdG28资讯网——每日最新资讯28at.com

本文链接:http://www.28at.com/showinfo-26-49475-0.htmlJS小知识,分享五个不常用但又很重要的原生API

声明:本网页内容旨在传播知识,不代表本站观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。

显示全文

上一篇:又老性能又差,为什么好多公司依然选择 RabbitMQ?

下一篇:Python实现定时任务的利器Apscheduler

最新热点