Change color of specific words in textarea

前端 未结 4 1470

I\'m building a Sql query builder and would like to change the text color of a word in a textarea when the user types in words like SELECT, FROM, WHERE.

I\'ve searche

相关标签:
4条回答
  • 2020-11-29 02:37

    JS FIDDLE CODE

    HTML-

    <div id="board" class="original" contenteditable="true"></div>
    <div id="dummy" class="original"></div>
    

    CSS-

    .original {
       position:absolute;width: 50%; margin: 0 auto; padding: 1em;background: #fff;height:100px;margin:2px;border:1px solid black;color:#fff;overflow:auto;
    }
    
    #dummy{
      color:black;
    }
    #board{
      z-index:11;background:transparent;color:transparent;caret-color: black;
    }
    .original span.highlighted {
        color:red;
    }
    

    JAVASCRIPT -

    var highLightedWord = ["select","insert","update","from","where"];
    var regexFromMyArray = new RegExp(highLightedWord.join("|"), 'ig');
    $('#board').keyup(function(event){
     document.getElementById('dummy').innerHTML = $('#board').html().replace(regexFromMyArray,function(str){
     return '<span class="highlighted">'+str+'</span>'
     })
    })
    var target = $("#dummy");
      $("#board").scroll(function() {
        target.prop("scrollTop", this.scrollTop)
              .prop("scrollLeft", this.scrollLeft);
      });
    
    0 讨论(0)
  • 2020-11-29 02:40

    You can't change the colours of words in a <textarea>, but you can use the contenteditable attribute to make a <div>, <span>, or <p> look like a <textarea>.

    To do this you can use a JavaScript plugin, but if you want to create a new one, the code below may help you.

    For this purpose, you need to get any word in the text. Then check that if it's a SQL keyword.

    // SQL keywords
    var keywords = ["SELECT","FROM","WHERE","LIKE","BETWEEN","NOT LIKE","FALSE","NULL","FROM","TRUE","NOT IN"];
    // Keyup event
    $("#editor").on("keyup", function(e){
      // Space key pressed
      if (e.keyCode == 32){
        var newHTML = "";
        // Loop through words
        $(this).text().replace(/[\s]+/g, " ").trim().split(" ").forEach(function(val){
          // If word is statement
          if (keywords.indexOf(val.trim().toUpperCase()) > -1)
            newHTML += "<span class='statement'>" + val + "&nbsp;</span>";
          else
            newHTML += "<span class='other'>" + val + "&nbsp;</span>"; 
        });
        $(this).html(newHTML);
    
        // Set cursor postion to end of text
        var child = $(this).children();
        var range = document.createRange();
        var sel = window.getSelection();
        range.setStart(child[child.length-1], 1);
        range.collapse(true);
        sel.removeAllRanges();
        sel.addRange(range);
        this.focus();
      }
    });
    #editor {
        width: 400px;
        height: 100px;
        padding: 10px;
        background-color: #444;
        color: white;
        font-size: 14px;
        font-family: monospace;
    }
    .statement {
        color: orange;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="editor" contenteditable="true"></div>

    0 讨论(0)
  • 2020-11-29 02:45

    you can use this code

    <code contenteditable="true">
      <span style="color: orange">SELECT</span> *
      <span style="color: orange">FROM</span>
       TABLE
      <span style="color: orange">WHERE</span>
      id = 2
    </code>
    
    0 讨论(0)
  • 2020-11-29 02:51

    With Vanilla JS, you can do it as:

        // SQL keywords
        var keywords = ["SELECT", "FROM", "WHERE", "LIKE", "BETWEEN", "UNION", "FALSE", "NULL", "FROM", "TRUE", "NOT", "ORDER", "GROUP", "BY", "NOT", "IN"];
        // Keyup event
        document.querySelector('#editor').addEventListener('keyup', e => {
        // Space key pressed
        if (e.keyCode == 32) {
            var newHTML = "";
            // Loop through words
            str = e.target.innerText;
            chunks = str
              .split(new RegExp(
                keywords
                  .map(w => `(${w})`)
                  .join('|'), 'i'))
              .filter(Boolean),
            markup = chunks.reduce((acc, chunk) => {
              acc += keywords.includes(chunk.toUpperCase()) ?
              `<span class="statement">${chunk}</span>` :
              `<span class='other'>${chunk}</span>`
              return acc
            }, '')      
            e.target.innerHTML = markup;
    
            // Set cursor postion to end of text
            //    document.querySelector('#editor').focus()
            var child = e.target.children;
            var range = document.createRange();
            var sel = window.getSelection();
            range.setStart(child[child.length - 1], 1);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
            this.focus();
                
            }
        });
            #editor {
                width: 400px;
                height: 100px;
                padding: 10px;
                background-color: #444;
                color: white;
                font-size: 14px;
                font-family: monospace;
            }
            .statement {
                color: orange;
            }
    <div id="editor" contenteditable="true"></div>

    0 讨论(0)
提交回复
热议问题