Javascript 文本区域或文本输入中的多色文本突出显示
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4845813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multicolor Text Highlighting in a Textarea or Text Input
提问by oneself
I'd like to set text in a textarea or text input using different colors (one or the other is fine, I don't need both). Think of something like simple syntax highlighting. So, let's say I have some keywords defined. I'd like those words to be colored a different color as the user types into the textarea or text input
我想在 textarea 中设置文本或使用不同颜色的文本输入(一种或另一种都可以,我不需要两者)。想想像简单的语法高亮这样的东西。所以,假设我定义了一些关键字。当用户在 textarea 或 text input 中键入时,我希望这些单词被着色为不同的颜色
I understand this needs to be some combination of CSS, Javascript, and maybe some pixie dust. I wondering which direction I need to dig into to find out how this can be done.
我知道这需要 CSS、Javascript 和一些小精灵的某种组合。我想知道我需要深入研究哪个方向来找出如何做到这一点。
Thank you
谢谢
回答by Tim Down
No, you can't do this in a textarea or text input. Any CSS text-related property will affect the whole text within the the textarea/input. You'll need an editable element or document to achieve syntax highlighting. Example (works in all recent browsers; the last major browser not to support contenteditable
was Firefox 2.0):
不,您不能在 textarea 或文本输入中执行此操作。任何与 CSS 文本相关的属性都会影响 textarea/input 中的整个文本。您需要一个可编辑的元素或文档来实现语法高亮显示。示例(适用于所有最近的浏览器;最后一个不支持的主要浏览器contenteditable
是 Firefox 2.0):
<code contenteditable="true">
<span style="color: blue">var</span> foo = <span style="color: green">"bar"</span>;
</code>
回答by Zhang Kai Yu
Are you finding this?
你在找这个吗?
Use jQuery.colorfy
使用 jQuery.colorfy
Code: https://github.com/cheunghy/jquery.colorfy
代码:https: //github.com/cheunghy/jquery.colorfy
Demo: http://cheunghy.github.io/jquery.colorfy/
演示:http: //cheunghy.github.io/jquery.colorfy/
Screencast: https://www.youtube.com/watch?v=b1Lu_qKrLZ0
截屏视频:https: //www.youtube.com/watch?v=b1Lu_qKrLZ0
回答by Provision
This can actually be done by using styling inside of the tag, this is a reference from one of my websites where i have done this
这实际上可以通过在标签内使用样式来完成,这是我完成此操作的网站之一的参考
<input style="border-radius: 5px; background-color: #000000; color: #ff0000; border-color:
blue;" class="form-control" name="firstname" placeholder="What you were looking for?"
type="text"
required autofocus />
回答by Macumbaomuerte
you can simply make a SPAN tag for selecting some part of the text, for example:
您可以简单地制作一个 SPAN 标签来选择文本的某些部分,例如:
Some <span style="color:#FF3333">text</span> here
Wich will make the word text look in red
Wich 将使文字文本显示为红色