JavaScript 按文本实际行拆分时,如何保留内部 span 标签?
可以保留内部 span:保留原始 DOM,让浏览器完成换行,再用 Range 找出每行的文本范围,复制范围内的内容及必要的祖先标签,最后放入独立的行容器。
这样,跨行的 <span class="my_class"> 会在相关的各行中分别生成对应标签,文字和标点仍按原始顺序保留。
为什么现有实现会丢失标签
问题出在这句:
originalText = paragraph.textContent.replace(/\s+/g, ' ').trim();
textContent 只返回文字。执行后,内部 span 的位置、嵌套关系和属性都会丢失,后续无法仅凭这个字符串恢复。
如果内部元素影响字体或字符间距,用不含这些元素的临时 span 测量,得到的换行结果也可能不同。父容器的 scrollWidth 包含溢出内容,不能直接代表段落实际可用的排版宽度。
因此,需要保存原始节点,在原始结构下读取布局。
实现思路
处理顺序如下:
- 初始化时缓存段落内部的原始 DOM。
- 每次计算前恢复原始 DOM,让浏览器正常排版。
- 使用
TreeWalker遍历文本节点,通过Range.getClientRects()读取字符位置。 - 根据字符的纵向位置识别换行边界。
- 复制各行范围,补回必要的外层标签,再添加行容器。
- 使用
ResizeObserver监听段落宽度变化,字体加载完成后也重新计算。
这份实现适用于题目中的普通文本和内联 span,要求水平从左到右排版、使用 white-space: normal,且同一行文字具有一致的垂直字体指标。若内部元素使用不同字号、vertical-align、内联块或会改变尺寸的装饰,需要进一步调整行识别和测量逻辑。
代码示例
给段落和行容器添加样式:
.cmp-parallax-text-highlight__paragraph {
white-space: normal;
text-indent: 0;
}
.cmp-parallax-text-highlight__paragraph_line {
display: block;
}
下面的 JavaScript 可以替换原来的分行逻辑。请在段落节点已经存在后执行,例如使用带 defer 的脚本。
const paragraphs = Array.from(
document.querySelectorAll('.cmp-parallax-text-highlight__paragraph')
);
// Cache the original DOM before adding line wrappers.
const originals = new Map();
for (const paragraph of paragraphs) {
const source = document.createDocumentFragment();
for (const child of paragraph.childNodes) {
source.appendChild(child.cloneNode(true));
}
originals.set(paragraph, source);
}
function getTextNodes(root) {
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_TEXT
);
const nodes = [];
let node;
while ((node = walker.nextNode())) {
if (node.data.length > 0) {
nodes.push(node);
}
}
return nodes;
}
function findLineRanges(paragraph) {
const nodes = getTextNodes(paragraph);
if (nodes.length === 0) return [];
const starts = [{ node: nodes[0], offset: 0 }];
const probe = document.createRange();
let lineTop = null;
for (const node of nodes) {
let offset = 0;
// Range offsets use UTF-16 code units.
for (const character of node.data) {
const nextOffset = offset + character.length;
// Under white-space: normal, whitespace is retained in the
// output ranges but is not used to identify a new line.
if (!/^\s$/u.test(character)) {
probe.setStart(node, offset);
probe.setEnd(node, nextOffset);
const rect = Array.from(probe.getClientRects()).find(
item => item.width > 0 && item.height > 0
);
if (rect) {
if (lineTop === null) {
lineTop = rect.top;
} else if (Math.abs(rect.top - lineTop) > 1) {
starts.push({ node, offset });
lineTop = rect.top;
}
}
}
offset = nextOffset;
}
}
// Leave hidden paragraphs or whitespace-only content unchanged.
if (lineTop === null) return [];
const lastNode = nodes[nodes.length - 1];
const finalEnd = {
node: lastNode,
offset: lastNode.data.length
};
return starts.map((start, index) => ({
start,
end: starts[index + 1] || finalEnd
}));
}
function cloneLineContents(paragraph, start, end) {
const range = document.createRange();
range.setStart(start.node, start.offset);
range.setEnd(end.node, end.offset);
let fragment = range.cloneContents();
let ancestor = range.commonAncestorContainer;
if (ancestor.nodeType === Node.TEXT_NODE) {
ancestor = ancestor.parentNode;
}
// cloneContents() does not copy the common ancestor itself.
// Restore any ancestor chain inside the paragraph.
while (ancestor && ancestor !== paragraph) {
const wrapper = ancestor.cloneNode(false);
wrapper.appendChild(fragment);
fragment = document.createDocumentFragment();
fragment.appendChild(wrapper);
ancestor = ancestor.parentNode;
}
return fragment;
}
function splitParagraph(paragraph) {
paragraph.replaceChildren(
originals.get(paragraph).cloneNode(true)
);
const lines = findLineRanges(paragraph);
if (lines.length === 0) return;
const result = document.createDocumentFragment();
// Build all fragments before replacing the measured DOM.
for (const { start, end } of lines) {
const line = document.createElement('span');
line.className =
'cmp-parallax-text-highlight__paragraph_line';
line.appendChild(cloneLineContents(paragraph, start, end));
result.appendChild(line);
}
paragraph.replaceChildren(result);
}
function renderAll() {
for (const paragraph of paragraphs) {
splitParagraph(paragraph);
}
}
let frame = null;
function scheduleRender() {
if (frame !== null) return;
frame = requestAnimationFrame(() => {
frame = null;
renderAll();
});
}
renderAll();
const previousWidths = new WeakMap();
const observer = new ResizeObserver(entries => {
let widthChanged = false;
for (const entry of entries) {
const width = entry.contentRect.width;
const previous = previousWidths.get(entry.target);
previousWidths.set(entry.target, width);
if (
width > 0 &&
(previous === undefined || Math.abs(width - previous) > 0.5)
) {
widthChanged = true;
}
}
if (widthChanged) scheduleRender();
});
for (const paragraph of paragraphs) {
observer.observe(paragraph);
}
if (document.fonts) {
document.fonts.ready.then(scheduleRender);
}
这里没有通过字符串拼接生成内部 HTML。每行内容都复制自原始节点,class 等属性也会随对应元素保留。
为什么还要补回祖先标签
仅调用 Range.cloneContents() 还不够。假设某行全部位于下面这个 span 的一个文本节点中:
<span class="my_class">sit amet, consectetur adipiscing elit.</span>
如果范围只选中了其中的 adipiscing elit.,复制结果可能只有文本,因为外围 span 不在选中的内容范围内。
示例中的 cloneLineContents() 会从 commonAncestorContainer 向上检查,直到段落节点,将缺少的祖先元素逐层补回。即使整行都位于同一个内部 span 中,也能保留其样式。
在某个合适的容器宽度下,结果可能类似:
<p class="cmp-parallax-text-highlight__paragraph">
<span class="cmp-parallax-text-highlight__paragraph_line">Lorem ipsum dolor <span class="my_class">sit amet, consectetur </span></span>
<span class="cmp-parallax-text-highlight__paragraph_line"><span class="my_class">adipiscing elit. </span>Quisque fermentum sem<span class="my_class"> </span></span>
<span class="cmp-parallax-text-highlight__paragraph_line"><span class="my_class">magna, vitae pharetra</span> neque </span>
</p>
具体断行由实际字体、容器宽度和 CSS 决定。边界空格可能留在上一行末尾,也可能形成仅含空格的内部 span;在上述 white-space: normal 的条件下,它们通常不会显示为额外的行首空白。不要为了清理结构而逐行调用 trim(),否则可能改变原始文本。
使用时需要注意什么
字体和样式会影响分行。示例通过 rect.top 判断是否进入下一行,1px 是用于容忍位置误差的阈值,并非适用于所有排版的通用规则。混合字号、上标、下标、竖排、双向文本、<br> 或内联块需要单独处理。内部 span 如果带有水平 padding、margin 或 border,跨行复制后新增的盒子边缘也可能改变宽度。
行容器主要用来承载动画。给它添加字体、字距、padding 等影响尺寸的样式,可能使复制后的文本再次换行。重新生成行节点后,依赖旧节点的动画实例也需要重新绑定。
复制 DOM 会改变节点身份。cloneNode() 和 cloneContents() 不会复制通过 addEventListener() 注册的监听器。内部元素需要交互时,可以在稳定的父节点上使用事件委托。若内部元素带有 id,跨行复制可能产生重复 id,需要另行处理。
原始内容需要独立保存。每次重排都应从缓存的原始 DOM 开始,避免在已有行容器外继续嵌套。如果业务会动态更新段落内容,也应同步更新缓存,再调用 scheduleRender()。
ResizeObserver 能处理容器宽度变化,包括常见的屏幕旋转场景。字号、字距或字体在宽度不变时发生变化,也需要主动重新计算。组件销毁时,应调用 observer.disconnect(),并取消尚未执行的动画帧。
原示例末行的 <span> 应改为 </span>;标点也应保持原始样式归属,例如原本位于 my_class 内的句号,拆分后仍应留在对应标签内。
备注:内容仅供参考。
