每次我调用Element.getClientRects()时,它仅返回一个DOMRect对象的集合。
Element.getClientRects()何时返回多个DOMRect对象的集合?

function handleClick() {
  console.log(event.target.getClientRects())
}
<ul
  style="border: 1px solid black;"
  onclick="handleClick()"
>
    <li>Click the text to see in console</li>
</ul>

最佳答案



当元素具有多个border-boxes(例如内联元素)时,则Element.getClientRects()返回多个DOMRect对象。一个例子:

let p = document.querySelector('p');
let span = document.querySelector('span');

console.log(p.getClientRects().length);
console.log(span.getClientRects().length);
p {
  border: 1px solid green;
}
span {
  border: 1px solid red;
}
<p>
  This is a paragraph with
  <span>Span Element having a looooooooooooooooooooooo nnnnnnnnnnnnnnnnnnnn ggggggggggggggggg text</span>
</p>


也是,返回值取决于屏幕分辨率。大小越小,CSS border-boxes的数量越小。

09-25 17:48