Change color of specific words in textarea

試著忘記壹切 提交于 2019-12-17 08:51:17

问题


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 searched around a bit and beyond this (https://jsfiddle.net/qcykvr8j/2/) I unfortunately do not come any further.

Example code

HTML:

<textarea name="query_field_one" id="query_field_one" onkeyup="checkName(this)"></textarea>

JS:

    function checkName(el)
    {
    if (el.value == "SELECT" || 
    el.value == "FROM" || 
    el.value == "WHERE" || 
    el.value == "LIKE" || 
    el.value == "BETWEEN" || 
    el.value == "NOT LIKE" || 
    el.value == "FALSE" || 
    el.value == "NULL" || 
    el.value == "TRUE" || 
    el.value == "NOT IN")
    {
      el.style.color='orange'

    }
    else {
      el.style.color='#FFF'

    }
  }

JSFiddle:

https://jsfiddle.net/qcykvr8j/2/

But this example deletes the color when I type further.

What I want is this:

I've tried something with Keyup in combination with Contains in jQuery but that did not result in much.

Keyup: https://api.jquery.com/keyup/

Contains: https://api.jquery.com/contains-selector/

I hope someone can help me with an example or sites where I can find more information .

Regards, Jens


回答1:


You can't change color words in textarea, but you can use contenteditable attribute to change content text of element (like div, p, span). To do this work you can use javascript plugin, but if you want to create it, you can use this code.

For this purpose, you need to get any word in text. Then check that if target word is in SQL statement highlight it.

// 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();
  }
});

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



回答2:


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);
  });


来源:https://stackoverflow.com/questions/37139076/change-color-of-specific-words-in-textarea

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