我有一个 contenteditable div。我想要 div 中的功能如下:
当我点击红色 anchor 标签时,我要写的新文本将是红色的,当点击蓝色时,文本应该开始用蓝色书写。
注意:当点击蓝色 anchor 时,用红色书写的内容不应该变成蓝色,反之亦然。这意味着在 div 中,我们最终将使用红色和蓝色书写文本。我可以在 div 中的任何位置写入文本。
$("#red").click(function () {
$("div").addClass("red");
$("div").removeClass("blue");
});
$("#blue").click(function () {
$("div").addClass("blue");
$("div").removeClass("red");
});
问题:我的代码中的问题是,当我点击红色时,它会将 div 的所有颜色更改为红色,与蓝色相同。
最佳答案
对于此类用例,您可以使用 HTML 编辑 API。此处引用:https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html
简而言之,使用 execCommand
和 styleWithCSS
来实现你想要的。 styleWithCSS
可让您控制是否应通过 execCommand 方法将 CSS 或 HTML 格式生成到文档中。传递 true
以使用 CSS 样式而不是生成字体标签。
在下面尝试...
示例片段:
var
red = document.getElementById("red"),
blue = document.getElementById("blue"),
reset = document.getElementById("reset")
;
red.addEventListener("click", function() { setColor("#f00"); });
blue.addEventListener("click", function() { setColor("#00f"); });
reset.addEventListener("click", function() { setColor("#000"); });
function setColor(color) {
document.execCommand('styleWithCSS', false, true);
document.execCommand('foreColor', false, color);
}
<a href="#" id="red">Red</a> | <a href="#" id="blue">Blue</a> | <a href="#" id="reset">Reset</a> |
<p contentEditable="true" id="ce">this is some text</p>
这将生成应用了 CSS 的 HTML,如下所示:
<p contenteditable="true">
this is <span style="color: #f00;">some</span> text
</p>
希望对您有所帮助。
.
关于javascript - 更改 contenteditable div 中文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31582205/