我可以使用Range.getClientRects()来确定文本节点的每个包装线的坐标:
var range = document.createRange(),
cr,
r,
div;
range.selectNode(document.body.childNodes[0]);
cr= range.getClientRects();
for(r = 0 ; r < cr.length ; r++) {
div = document.createElement('div');
div.style.cssText= `position: absolute;
left : ${cr[r].left}px;
top : ${cr[r].top}px;
width : ${cr[r].width}px;
height : ${cr[r].height}px;
border : 1px solid green;
`;
document.body.appendChild(div);
}
&#13;
body {
width: 300px;
font: 13px Arial;
text-align: center;
}
* {
box-sizing: border-box;
}
&#13;
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
&#13;
但是,似乎并不是确定每一行的文本内容的简单方法。
我可以通过一次一个地添加每个单词直到它包装来强制解决方案,就像我在下面的代码片段中所做的那样:
var div = document.querySelector('div'),
s = div.textContent.split(' '),
word,
line = '',
lines = [],
h = 0;
div.textContent = '';
while(s.length) {
word = s.shift() + ' ';
div.textContent += word;
if(div.clientHeight !== h) {
h = div.clientHeight;
if(line) {
lines.push(line);
}
line= '';
}
line += word;
}
lines.push(line);
console.log(lines);
&#13;
body {
width: 300px;
font: 13px Arial;
}
* {
box-sizing: border-box;
}
&#13;
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
&#13;
但是在处理多个元素节点时,这会很快变得混乱。
有更好的方法吗?