如何将部分文本包装在具有 'display: flex and justify-content: space-between' 样式的节点中?

How to wrap part of the text in a node that has 'display: flex and justify-content: space-between' styling?

我目前正在编写一个 Firefox 扩展,它使用模糊搜索来突出显示网页上的单词。

通过创建包含匹配项的范围,然后将范围的内容包裹在自定义元素周围来完成突出显示。这种方法在我看来相当于把文本节点的文本拆分出来,手动复制到一个新创建的节点上。

插件的预发布版本运行良好,但是有一种 css 样式我无法处理:display: flex; justify-content: space-between。这里的问题是,当我部分包裹这样样式的节点的内容时,呈现的文本会失去其完整性。

下面是一个简单的演示。你可以看到,在格式化开始的 1 秒后,第 1 段被隔开,而第 2 段保持不变。

有人可以针对这个问题提出 solution/workaround 的建议吗?我想保持网页的 css 不变,因此修改元素的样式是不可能的。我检查了 mark.js API ,它也无法处理这种情况。我想知道浏览器内置的 ctrl-f 突出显示所有搜索栏如何处理这个问题..

function wrapRange(range){
  const markedNode = document.createElement('mark');
  range.surroundContents(markedNode);
}

setTimeout(() => { 
  document.querySelectorAll('p').forEach(node => {
    const range = new Range();
    range.setStart(node.firstChild, 0);
    range.setEnd(node.firstChild, 3);
    wrapRange(range);
  });
}, 1000);
.problematicClass {
  display: flex;
  justify-content: space-between;
}
mark {
  background-color: red;
}
<p class="problematicClass">Lorem ipsum</p>
<p>Lorem ipsum</p>

可以修改html吗?您是否需要将原始文本保留在带有 problematicClass 的元素中? 简单的解决方案是在 ex 中包装文本块。 <span>.

Flex 始终负责自布局和子布局。如果您不希望它们受到父节点 flex-settings 的影响,则必须在子节点周围添加一个包装器(即使它们是文本节点)。

The specification describes a CSS box model optimized for user interface design. In the flex layout model, the children of a flex container can be laid out in any direction, and can “flex” their sizes, either growing to fill unused space or shrinking to avoid overflowing the parent. Both horizontal and vertical alignment of the children can be easily manipulated. Nesting of these boxes (horizontal inside vertical, or vertical inside horizontal) can be used to build layouts in two dimensions.

来源:https://drafts.csswg.org/css-flexbox-1/

浏览器在完全不同的级别标记搜索 (CTRL+F) 的高亮显示,并且不会注入 html 代码。

你想做什么,可以通过选择 API 来解决,但请记住,只有 Firefox 一次支持多个选择范围。

查看示例:https://developer.mozilla.org/en-US/docs/Web/API/Selection/addRange#Result