【问题标题】:Highlight text as you type on textarea在 textarea 上键入时突出显示文本
【发布时间】:2011-03-17 23:39:43
【问题描述】:

我正在尝试创建一个文本区域,当用户在其中键入时会突出显示一些关键字。我了解 textarea 只能支持纯文本,并且我必须使用“富文本”编辑器才能实现这一点。我想要一些非常简单的东西,而不是那些臃肿的“富编辑器”。有任何想法吗?

谢谢!

【问题讨论】:

  • 你的意思是,你输入了一些东西,它试图猜测你在找什么?

标签: javascript jquery html textarea highlight


【解决方案1】:

这是一个 sn-p,它为您提供了正在寻找的基础知识:

<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>

基本概念是&lt;textarea&gt;(顶部)是透明的,而底部的&lt;div&gt; 包含“丰富/高亮”版本。在换行方面还有改进的余地,但你明白了。快乐突出!

信用: preg_quote 函数来自 Kevin van Zonneveld http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_preg_quote/

【讨论】:

  • 太棒了!这似乎是所有 StackOverflow 中唯一真正告诉您 CodeMirror(以及其他喜欢它的编辑器!)如何工作的答案! :)
【解决方案2】:

看看这个:http://codemirror.net/

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 1970-01-01
    • 2013-12-29
    相关资源
    最近更新 更多