在contenteditable div中更改文本的颜色 [英] Change color of the text in contenteditable div

查看:123
本文介绍了在contenteditable div中更改文本的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

演示在这里

I有一个满足的div。我希望div中的功能如下:

I have a contenteditable div. I want the functionality in the div as follows:

当我点击红色锚标签时,我要写的新文本将是红色,当点击蓝色时,文本应该开始用蓝色书写。

注意:当点击蓝色锚点时,用红色书写的内容不应该变成蓝色,反之亦然。这意味着在div中,我们最终会有红色和蓝色的文字。我可以在div中的任何地方写文本。

When I click on red anchor tag, the new text that I will write will be of red color, and when clicked blue, the text should start writing with blue color.
Note: When click on the blue color anchor, the content written in red color should not get blue and vice versa. This means that in the div, we will have text written in red and blue color at last. I can write text anywhere in the div.

$("#red").click(function () {
    $("div").addClass("red");
    $("div").removeClass("blue");
});

$("#blue").click(function () {
    $("div").addClass("blue");
    $("div").removeClass("red");
});

问题:我的代码中的问题是,当我点击红色时,它会改变所有的颜色div为红色,与蓝色相同。

Problem: The problem in my code is that when i click on red, it changes all the color of the div in red and same as of blue.

推荐答案

您可以使用HTML编辑API来处理此类用例。参考此处: https://dvcs.w3.org/hg/编辑/ raw-file / tip / editing.html

You could make use of HTML editing APIs for such use-cases. Reference here: https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html

简而言之,请使用 execCommand styleWithCSS 来实现你想要的。 styleWithCSS 将允许您控制是否应该通过execCommand方法将CSS或HTML格式生成到文档中。传递 true 以使用CSS样式而不是生成字体标记。

In short, use the execCommand along with styleWithCSS to achieve what you want. styleWithCSS will let you control whether CSS or HTML formatting should be generated by the execCommand method into the document. Pass true to use the CSS styling instead of generating the font tag.

在下面尝试...

示例代码段

Example Snippet:

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,如下所示:

This will generate HTML with CSS applied, like this:

<p contenteditable="true">
    this is <span style="color: #f00;">some</span> text
</p>

希望有所帮助。

这篇关于在contenteditable div中更改文本的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆