[英]Highlight text as you type on textarea
I'm trying to create a textarea that will highlight some keywords as the user types in there. 我正在尝试创建一个textarea,它将突出显示用户在那里键入的一些关键字。 I understant textarea can only support plain text and that I have to use a 'rich text' editor in order to achieve this.
我理解textarea只能支持纯文本,我必须使用“富文本”编辑器才能实现这一目标。 I would like something really simple though and not the bloated 'rich editors' out there.
我想要一些非常简单的东西,而不是那些臃肿的“富有编辑”。 Any ideas?
有任何想法吗?
Thanks! 谢谢!
Here is a snippet that gives you the basics of what are looking for: 这是一个片段,为您提供所需内容的基础知识:
<style>
.textarea { font-family:arial; font-size:12px; border:0; width:700px; height:200px; }
.realTextarea { margin:0; background:transparent; position: absolute; z-index:999; }
.overlayTextarea { margin:0; position:absolute; top:1; left:1; z-index:998; }
.textareaBorder { border:groove 1px #ccc; position:relative; width:702px; height:202px; }
.highlight { background: yellow; }
</style>
<script>
var _terms = ['January', 'February', 'March']; // YOUR SEARCH TERMS GO HERE //
function preg_quote( str ) {
return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}
function doit() {
var s = myTextarea.value;
for (i=0; i<_terms.length; i++)
s = s.replace( new RegExp( preg_quote( _terms[i] ), 'gi' ), '<span class="highlight">' + _terms[i] + '</span>' );
myOtherTextarea.innerHTML = s.replace( new RegExp( preg_quote( '\r' ), 'gi' ), '<br>' );
}
</script>
<div class="textarea textareaBorder">
<textarea id="myTextarea" onkeyup="doit();" class="textarea realTextarea"></textarea>
<div id="myOtherTextarea" class="textarea overlayTextarea"></div>
</div>
The basic concept is that the <textarea>
(on top) is transparent and the <div>
underneath contains the "rich / hightlighted" version. 基本概念是
<textarea>
(在顶部)是透明的,下面的<div>
包含“rich / hightlighted”版本。 There is room for improvement when it comes to wrapping text but you get the idea. 在包装文本方面还有改进的余地,但你明白了。 Happy Highlighting!
快乐突出!
Credit: The preg_quote function is from Kevin van Zonneveld http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_preg_quote/ 图片来源:preg_quote函数来自Kevin van Zonneveld http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_preg_quote/
看看这个: http : //codemirror.net/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.