您可以使用HTML编辑API来处理此类用例.参考这里:
/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);
}
Red | Blue | Reset |
this is some text
这将生成应用了CSS的HTML,如下所示:
this is some text
希望有所帮助.
.