获取使用 document.write 插入的 DOMElement 的维度

Get dimension of a DOMElement that was inserted using document.write

本文关键字:DOMElement 插入 write document 获取      更新时间:2023-09-26

网站进行返回HTML代码段的Web服务调用。站点使用 document.write 将响应 HTML 附加到文档中。现在,如果我想弄清楚刚才插入的元素的尺寸(宽度,高度),我该如何实现?

由于您使用的是 document.write,因此正文中的内容将被新内容替换。我假设正文中只放置了一个元素,因此我们得到该元素document.body.childNodes[0].如果添加许多元素,请为它们提供一个 id,或通过标签或其他内容选择它们。

DOM 中的每个元素都有一个名为 getBoundingClientRect 的函数,它将为您提供一个具有宽度和高度属性的对象。

var dimensions = document.body.childNodes[0].getBoundingClientRect();
console.log(dimensions);

见 https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect