javascript - 我如何使用 jquery 在文本字段中添加不同的字体颜色

标签 javascript jquery html css

我有一个文本字段,有人可以在其中输入字符串。

根据用户在此字符串中键入的内容,我想更改为特定单词的颜色。类似于语法高亮。

例如,用户可以输入:

something::anotherthing

应该翻译成

<span class=color1>something</span><span class=color2>::</span>anotherthing 

在文本字段中怎么可能,因为 html 不会在那里翻译?

最佳答案

使用content editable div 或其他支持元素上的属性。这就是大多数在线 html 编辑器的工作方式。您将获得对选择文本区域和更改其颜色和其他属性的内置支持,以及撤消/重做支持。

live working example :

HTML

<div contenteditable="true">
    change the color!
</div>


<button>
    red
</button>
<button>
    blue
</button>
<button>
    green
</button>

JS (jQuery)

$('button').click(function(){
document.execCommand('ForeColor', false, $(this).html());
});

关于javascript - 我如何使用 jquery 在文本字段中添加不同的字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25470811/

相关文章:

html - 使用 float with canvas 的 CSS 布局问题

javascript - 日期范围还可以过滤另一个月份的同一天吗?

javascript - 我的 html 脚本标签没有链接到我的外部 javascript

javascript - 使用 ShinyBS 实现 Shiny 的响应式(Reactive)工具提示BS

javascript - 在js中重新启用对键盘的访问

jquery - Bootstrap 轮播控件不起作用

javascript - 在 JQuery FileUpload 中返回删除成功

javascript - 在浏览器中使用 axios 处理重定向

html - 带百分比的最小和最大尺寸

html - 位置div在底部