为什么 Range.getBoundingClientRect() returns 0 用于 textarea 内的范围?
Why Range.getBoundingClientRect() returns 0 for range inside textarea?
我有 <textarea>
元素并在其中创建范围:
- 通过
document.createRange()
创建新范围
- 通过
textarea.childNodes[0]
获取<textarea>
的唯一子节点
- 通过
range.setStart
和range.setEnd
设置范围开始和范围结束
然后我调用range.getBoundingClientRect()
:
let textarea = document.querySelector('textarea');
let node = textarea.childNodes[0];
let range = document.createRange();
range.setStart(node, 3);
range.setEnd(node, 5);
console.log(range.getBoundingClientRect());
<textarea>aa bb cc</textarea>
但我收到了 ClientRect
个全为零字段的对象,即 left = top = width = height = 0
。为什么这些字段为零?
请注意,如果我将 <textarea>
替换为通常的 div:
,一切正常
let textarea = document.querySelector('div');
let node = textarea.childNodes[0];
let range = document.createRange();
range.setStart(node, 3);
range.setEnd(node, 5);
console.log(range.getBoundingClientRect());
<div>aa bb cc</div>
<textarea>
是一个 replacement element
Objects inserted using the CSS content property are anonymous replaced
elements. They are "anonymous" because they don't exist in the HTML
markup.
我有 <textarea>
元素并在其中创建范围:
- 通过
document.createRange()
创建新范围
- 通过
textarea.childNodes[0]
获取 - 通过
range.setStart
和range.setEnd
设置范围开始和范围结束
<textarea>
的唯一子节点
然后我调用range.getBoundingClientRect()
:
let textarea = document.querySelector('textarea');
let node = textarea.childNodes[0];
let range = document.createRange();
range.setStart(node, 3);
range.setEnd(node, 5);
console.log(range.getBoundingClientRect());
<textarea>aa bb cc</textarea>
但我收到了 ClientRect
个全为零字段的对象,即 left = top = width = height = 0
。为什么这些字段为零?
请注意,如果我将 <textarea>
替换为通常的 div:
let textarea = document.querySelector('div');
let node = textarea.childNodes[0];
let range = document.createRange();
range.setStart(node, 3);
range.setEnd(node, 5);
console.log(range.getBoundingClientRect());
<div>aa bb cc</div>
<textarea>
是一个 replacement element
Objects inserted using the CSS content property are anonymous replaced elements. They are "anonymous" because they don't exist in the HTML markup.