Highlight text as you type on textarea

孤者浪人 提交于 2019-11-26 22:40:29

问题


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?

Thanks!


回答1:


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




回答2:


Take a look at this one : http://codemirror.net/



来源:https://stackoverflow.com/questions/3282505/highlight-text-as-you-type-on-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!