使用(out) execCommand自定义样式(如何处理重叠的标签)

custom styling with(out) execCommand (how to deal with overlapping tags)

本文关键字:处理 重叠 何处理 标签 样式 out execCommand 自定义 使用      更新时间:2023-09-26

因为execCommand不像预期的那样工作,所以我想自己构建一个类似的函数。应该可以对文本应用不同的样式。如果我想添加一个样式,这很容易,因为我可以简单地使用范围。例如,它让我在选择的周围放置一个span-tag。我还可以通过从当前光标位置删除父节点来删除标记。我唯一无法找到解决方案的是如何处理以下有重叠标签的情况:

案例一:

<span class="bold">This is some text</span> that goes on <span class="italic">and on until the end</span>

想象用户从some到until中选择文本并应用下划线。修改应该是这样的:

<span class="bold">This is <span class="unterline">some text</span></span><span class="underline"> that goes on </span><span class="italic"><span class="underline">and on until</span> the end</span>

案例B:

<span class="bold">This is some text</span> that goes on <span class="italic">and on until the end</span>

想象用户选择文本从一些到直到,并应用一个粗体。修改应该是这样的:

<span class="bold">This is some text that goes on </span><span class="italic"><span class="bold">and on until</span> the end</span> ... or similar valid output.

案例C:

<span class="color-orange">This is some text</span> that goes on <span class="color-blue">and on until the end</span>

假设用户从一些到直到选择文本并应用黄色。修改应该是这样的:

<span class="color-orange">This is </span><span class="color-yellow">some text that goes on and on until</span><span class="color-blue"> the end</span>

我怎么才能做到呢?因为这似乎是一个常见的问题,我很确定有人已经解决了这个问题,但我还没有找到任何东西。希望周围有人至少能给我指出正确的方向。谢谢你!

简短的回答:对于一般情况,很难明智而可靠地做到这一点。我开始为此工作一个Rangy模块,陷入困境并放弃了它。

看看几年前Google的Aryeh Gregor制定的HTML编辑规范草案。他还在他的规范中针对当时最新的浏览器编写了一个未优化的算法JavaScript实现。