我有带有预写消息的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做到吗?我认为应该是这样的:
....
(如果没有找到[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>
否则为,因为您不能像实际的HTML元素那样将
textarea
中的HTML元素视为实际的HTML元素以突出显示它们→您应该创建一个与textarea具有相同大小(字体大小等)的内存元素,执行上述操作,然后计算生成的span元素的位置,而不是在文本区域上的各个位置上应用一些高光覆盖,请注意如果窗口调整大小后它们会“跟进”……故事就这样了……这是一个jQuery插件来实现上述功能:
http://mistic100.github.io/jquery-highlighttextarea/