document.execCommand('removeFormat') 在 Chrome 上尝试删除 document.execCommand('hiliteColor') 设置的格式时失败



我正在通过document.execCommand('hiliteColor', false, '#d4ecff');为内容可编辑元素中的某些选定文本添加背景。

如果所选文本包含一些格式标记(例如<b></b>(,则对所选文本调用document.execCommand('removeFormat')不会删除所有格式。这就像背景颜色被传递到以前包含在<b></b>中的文本。

我在Chrome(版本100.0.4896.75-64位(和Brave(版本1.37.111 Chromium:100.0.48967.9-64位。在Firefox上,一切似乎都如预期一样。

以下是演示和复制步骤:https://jsfiddle.net/L82ogcf5/

PS:我知道不再建议使用document.execCommand(),所以请不要指出这一点。在该功能真正被弃用之前,这是无关紧要的(我们都知道这不会很快发生(

您正在添加hiliteColor!但是您想要删除任何格式
首先,<b>标记将被删除,只有在第二次单击后,hiliteColor才会被删除。

你想要的是:

// Remove hiliteColor, not other text formatting
btn2.onclick = () => document.execCommand("hiliteColor", false, "transparent");

示例:

const btn1 = document.querySelector("#btn1");
btn1.onclick = () => document.execCommand("hiliteColor", false, "red");
const btn2 = document.querySelector("#btn2");
btn1.onclick = () => document.execCommand("hiliteColor", false, "transparent");
#input {
margin-top: 1rem;
border: 1px solid;
}
Steps to reproduce:
<ol>
<li>Select all the text inside #input</li>
<li>Click on the button 1 - "add background colour"</li>
<li>Click on the button 2 - "remove format</li>
<li>Do you see a red background where the bold text was? Here's my bug</li>
</ol>
<button id="btn1">add background colour</button>
<button id="btn2">remove format</button>
<div id="input" contenteditable="true">
I am a real
<strong>nice test</strong> string
</div>

PS:遗憾的是,这项技术即将消亡(好吧,也许不会这么快,因为目前有太多应用程序是在contenteditable和execCommand上驱动的(。只是因为,由IE推出,随着竞争对手浏览器的兴起,他们在规格上都存在分歧,它慢慢地变成了一头无法处理的野兽。。。目前没有正在开发或编写规范的替代品,AFAIK。

首先,.execCommand被斩首,其次,在chrome中,removeFormat函数在层中工作。它删除了背景色,因为它是第一层格式。它只是删除了粗体文本上的粗体,因为这是第一层格式。尝试对高亮显示、粗体、斜体和下划线重复该命令4次。我想你是想创建一个格式可调的文本框吗?

就本例而言,解决方案将不是clearformatting,而是按照命令执行undo

或者,您可以再次执行execCommand,将高亮显示颜色设置为白色或透明或其他颜色。

最新更新