我有一个文本字段,有人可以在其中输入字符串。
根据用户在此字符串中键入的内容,我想更改为特定单词的颜色。类似于语法高亮。
例如,用户可以输入:
something::anotherthing
应该翻译成
<span class=color1>something</span><span class=color2>::</span>anotherthing
在文本字段中怎么可能,因为 html 不会在那里翻译?
最佳答案
使用content editable div 或其他支持元素上的属性。这就是大多数在线 html 编辑器的工作方式。您将获得对选择文本区域和更改其颜色和其他属性的内置支持,以及撤消/重做支持。
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/