【发布时间】: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