我有这个 HTML 代码,其中包含预先编写的消息。我的目标是当我聚焦/单击文本区域时,以黄色背景突出显示 [quote] [/quote] 之间的文本。
<textarea>
This is a test message.
[quote]Wise man said he is wise.[/quote] There could be more quotes too:
[quote]this is second quote [/quote]
He is correct.
</textarea>
是否可以用纯 Javascript 来实现?我认为应该是这样的:
textarea onfocus="function()">
- 查找 [quote][/quote] 之间的文本
- 对找到的文本应用黄色背景:background Color='#ffc'
...
(如果没有找到 [quote] [/quote],那么它什么也不做,即没有警告)。
最佳答案
因为你不能使用 <textatea>
来做到这一点我建议看一下
<div contenteditable>
</div>
这是一个例子:
var area = document.getElementById("area");
var text = area.innerHTML;
area.innerHTML = text.replace(/\[\s*quote.*\](.*)[^[]*\[\s*\/quote.*\]/ig, "<span>$1</span>");
[contenteditable]{
white-space:pre-wrap;
}
[contenteditable] span{
background:#ffc;
}
<div id="area" contenteditable>
This is a test message.
[quote]Wise man said he is wise.[/quote] There could be more quotes too:
[quote]this is second quote [/quote]
He is correct.
</div>
否则,因为您无法处理 textarea
内的 HTML 元素像实际的 HTML 元素一样,以便突出显示它们→您应该创建一个与文本区域大小(字体大小等)相同的内存中元素,执行上述操作,计算生成的 span 元素的位置,然后应用一些高亮覆盖在文本区域上的各个位置上,请注意,如果窗口大小调整,它们会“跟随”...并且故事会发生...
这里有一个 jQuery 插件来实现上述功能:
<强> http://mistic100.github.io/jquery-highlighttextarea/
关于Javascript 在文本区域内查找并突出显示 [quote][/quote] 之间的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32127590/