Ama*_*aur 4 html javascript css jquery
我有一个满足的div.我希望div中的功能如下:
当我点击红色锚标签时,我要写的新文本将是红色,当点击蓝色时,文本应该开始用蓝色书写.
注意:单击蓝色锚点时,用红色书写的内容不应该变为蓝色,反之亦然.这意味着在div中,我们最终会有红色和蓝色的文字.我可以在div中的任何地方写文字.
$("#red").click(function () {
$("div").addClass("red");
$("div").removeClass("blue");
});
$("#blue").click(function () {
$("div").addClass("blue");
$("div").removeClass("red");
});
Run Code Online (Sandbox Code Playgroud)
问题:我的代码中的问题是,当我点击红色时,它会将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);
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
这将生成应用了CSS的HTML,如下所示:
<p contenteditable="true">
this is <span style="color: #f00;">some</span> text
</p>
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.
.
| 归档时间: |
|
| 查看次数: |
5793 次 |
| 最近记录: |