在textarea上键入时突出显示文本 [英] Highlight text as you type on textarea

查看:114
本文介绍了在textarea上键入时突出显示文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个textarea,它会在用户键入内容时突出显示某些关键字。我理解textarea只能支持纯文本,并且我必须使用富文本编辑器才能实现此目的。我想要一些非常简单的东西,而不是那些臃肿的'富有编辑'。有任何想法吗?

I'm trying to create a textarea that will highlight some keywords as the user types in there. I understant textarea can only support plain text and that I have to use a 'rich text' editor in order to achieve this. I would like something really simple though and not the bloated 'rich editors' out there. Any ideas?

谢谢!

推荐答案

这是一段代码,寻找什么的基本知识:

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>

基本概念是< textarea> < div> 包含丰富/高亮版本。当涉及包装文本时,还有改进的空间,但你明白了。快乐突出!

The basic concept is that the <textarea> (on top) is transparent and the <div> underneath contains the "rich / hightlighted" version. There is room for improvement when it comes to wrapping text but you get the idea. Happy Highlighting!

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

这篇关于在textarea上键入时突出显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆