html contentEditable document.execCommand 更改选定的不透明度

2023-12-23

任何人都可以改变选定的 contentEditable 的不透明度。

我尝试了以下方法:

document.execCommand('foreColor', false, 'rgba(0,0,0,0.5)'); // with rgba
document.execCommand('foreColor', false, '80000000'); // with alpha hex

没有一个起作用。但我可以轻松地改变颜色:

document.execCommand('foreColor', false, '000000');

任何人都可以帮助我使用 document.execCommand 更改不透明度吗?

Update

进一步查找发现:

document.execCommand 'foreColor' 将字体标签添加到具有给定颜色的选定内容。但遗憾的是 HTML5 不支持 color 属性。

这就是问题所在吗?它的替代方案是什么?


您必须使用styleWithCSS命令,指定是否应通过 execCommand 方法在文档中生成 CSS 或 HTML 格式。

请参阅此处的规格:https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#the-stylewithcss-command https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html#the-stylewithcss-command .

所以,在这种情况下通过true使用 CSS 样式而不是生成font tag.

Snippet:

function setColor() {
    document.execCommand('styleWithCSS', false, true);
    document.execCommand('foreColor', false, "rgba(0,0,0,0.5)");
}
<p contentEditable="true" onmouseup="setColor();">this is some text</p>

这将生成应用了 CSS 的 HTML,如下所示:

<p contenteditable="true" onmouseup="setColor();">
    this is <span style="color: rgba(0, 0, 0, 0.498039);">some</span> text
</p>

希望有帮助。

.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

html contentEditable document.execCommand 更改选定的不透明度 的相关文章