Highlight text as you type on textarea

試著忘記壹切 提交于 2019-11-27 18:24:32
Todd H.

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/

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

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