我有一个可满足的部门。我希望div中的功能如下:
当我点击红色锚标签时,我将要写的新文本将是红色的,当单击蓝色时,文本应该开始用蓝色书写。
注意:单击蓝色锚点时,用红色写的内容不应该变成蓝色,反之亦然。这意味着,在div中,我们将最终用红色和蓝色书写文本。我可以在div的任何地方写短信。
$("#red").click(function () {
$("div").addClass("red");
$("div").removeClass("blue");
});
$("#blue").click(function () {
$("div").addClass("blue");
$("div").removeClass("red");
});问题:我的代码中的问题是,当我单击红色时,它会以红色和蓝色更改div的所有颜色。
发布于 2015-07-23 09:57:59
您可以为这种用例使用HTML编辑API。参考资料:https://dvcs.w3.org/hg/editing/raw-file/tip/editing.html
简而言之,使用execCommand和styleWithCSS来实现您想要的结果。styleWithCSS将允许您控制execCommand方法是否应该在文档中生成CSS或execCommand格式。传递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>希望这能有所帮助。
。
发布于 2015-07-23 09:43:18
,请试试这个
$("#red,#blue").click(function () {
$new = $("<div>", {
class: $(this).attr('id'),
contenteditable : 'true'
})
$("#my-contenteditable-div")
.append($new)
.children('div:last').focus();
});发布于 2015-07-23 09:37:34
这是我累的东西。我不知道你想达到什么目的。
我所做的: 1。我所做的是创建可编辑的跨度与红色和蓝色时,按钮被点击。2. span的负裕度,以减少“ ”所创造的空间
检查密码。小提琴
$("#red").click(function () {
$('<span>')
.attr('contenteditable','true')
.attr('class','red')
.html(' ')
.appendTo('#my-contenteditable-div')
});
$("#blue").click(function () {
$('<span>')
.attr('contenteditable','true')
.attr('class','blue')
.html(' ')
.appendTo('#my-contenteditable-div')
});.red
{
color:red;
}
.blue
{
color:blue;
}
div
{
height:100px;
border:1px solid red;
}
span{margin-left:-4px;}<a href="#" id="red">Red Pen</a><br/>
<a href="#" id="blue">Blue Pen</a><br/><br/><br/>
<div contenteditable="true" id="my-contenteditable-div"></div>
https://stackoverflow.com/questions/31582205
复制相似问题