javascript - 更改 contenteditable div 中文本的颜色

标签 javascript jquery html css

Demo is here

我有一个 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

简而言之,使用 execCommandstyleWithCSS 来实现你想要的。 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/

相关文章:

javascript - 如何在javascript中的选定单元格行上添加数据?

javascript - 我如何使用 JSDoc 记录一个对象?

javascript - Ajax 轮询 - 高效吗?

javascript - 如何使用js查找用户是否可以单击html中的给定按钮?

javascript - 单击索引页面上的项目时发布 ajax

javascript - 使用拼接从数组中删除元素

javascript - 文本区域中的奇怪问题

javascript - jQuery 代码无法识别表单提交值

javascript - anchor 在 chrome 和 safari 浏览器中不起作用

javascript - WCF Restfull WS post方法和HTML表单