【问题标题】:Weird behaviour with document.execCommand('insertHTML')document.execCommand('insertHTML') 的奇怪行为
【发布时间】:2021-02-19 05:08:08
【问题描述】:

我正在尝试通过添加这样的 CSS 类以编程方式突出显示所有出现的搜索词:

const style = document.createElement('style');
style.setAttribute('type', 'text/css');
style.innerHTML = `
.word-occurence {
  background: yellow;
  color: red;
  font-weight: bold;
  cursor: pointer;
}
`;
document.head.append(style)

document.designMode = "on";

window.getSelection().collapse(document, 0);

const word = 'Ubuntu';

while (window.find(word)) {
  document.execCommand('insertHTML', false, '<span class="word-occurence">' + window.getSelection() + '</span>');
  window.getSelection().collapseToEnd();

}
document.designMode = "off";

它几乎可以完美运行。当我在 Ubuntu 上的 Apache 服务器的默认 HTML 上尝试此操作时(可以在此处找到:http://bl.ocks.org/SunDi3yansyah/raw/c8e7a935a9f6ee6873a2/),“Ubuntu”一词的所有出现都在黄色背景上变为红色,但其中一个(第四个又名在他的段落开头的那个)得到了 CSS 内联样式而不是类。它缺少cursor: pointer,并且有一个额外的font-size: 14.6667px;

我知道document.execCommand 已被弃用,但我非常好奇:那里发生了什么?

【问题讨论】:

  • 在 Firefox 中对我来说很好。
  • 它也可以在 Chrome 中运行。

标签: execcommand


【解决方案1】:

在最新的 Chrome 版本中很容易发现这个错误。 insertHTML 命令在更改甚至删除内联元素(例如 [span])的属性时存在错误。在您的情况下,它会破坏作为文本节点的第一个单词的任何单词出现的属性。

没有官方规范,但有大量关于可能存在的错误和解决方法的信息。例如,我按照这篇文章的一些建议,通过将 [span] 替换为 [em] 标记来修复您的代码:Is there a way to keep execCommand("insertHTML") from removing attributes in chrome?

固定部分:

document.execCommand('insertHTML', false, '<em class="word-occurence">' + window.getSelection() + '</em>');

由于标签本身,单词变成了斜体,但类属性现在可以完美运行 - 没有额外的字体大小等。说到额外的字体大小。我发现问题不仅在于 Ubuntu 的第 4 次出现,它是 [p] 标签的第一个单词。位于自己的 [span] 元素内的徽标附近的第一个单词也受到此错误的影响。

总而言之,insertHTML 在使用 [span] 标记时存在各种错误。

以下是有关此主题的一些附加信息:https://w3c.github.io/editing/docs/execCommand/#fix-disallowed-ancestors

【讨论】:

  • 非常感谢您提供的参考和解决方案!
猜你喜欢
  • 1970-01-01
  • 2012-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2015-07-20
  • 2010-10-03
相关资源
最近更新 更多