更改textarea中特定单词的颜色

时间:2016-05-10 12:49:42

标签: javascript jquery html onkeyup

我正在构建一个Sql查询构建器,并希望在用户输入SELECT,FROM,WHERE等单词时更改textarea中单词的文本颜色。

我已经搜索了一下(https://jsfiddle.net/qcykvr8j/2/)我很遗憾没有再进一步了。

示例代码

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/

但是这个例子在我进一步输入时会删除颜色。

我想要的是:

Right way

我在jQuery中尝试将Keyup与Contains结合使用,但结果并不多。

密钥:https://api.jquery.com/keyup/

包含:https://api.jquery.com/contains-selector/

我希望有人可以帮助我找到一些我可以找到更多信息的例子。

此致,Jens

6 个答案:

答案 0 :(得分:18)

您无法更改textarea中的颜色词,但您可以使用contenteditable属性更改元素的内容文本(如div,p,span)。要完成这项工作,您可以使用javascript插件,但如果您想创建它,则可以使用此代码。为此,您需要在text中获取任何单词。然后检查目标单词是否在SQL语句中突出显示。

$("#editor").on("keydown keyup", function(e){
    if (e.keyCode == 32){
        var text = $(this).text().replace(/[\s]+/g, " ").trim();
        var word = text.split(" ");
        var newHTML = "";

        $.each(word, function(index, value){
            switch(value.toUpperCase()){
                case "SELECT":
                case "FROM":
                case "WHERE":
                case "LIKE":
                case "BETWEEN":
                case "NOT LIKE":
                case "FALSE":
                case "NULL":
                case "FROM":
                case "TRUE":
                case "NOT IN":
                    newHTML += "<span class='statement'>" + value + "&nbsp;</span>";
                    break;
                default: 
                    newHTML += "<span class='other'>" + value + "&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)[0].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>

答案 1 :(得分:1)

这不是这个问题的答案,但它回答了标题问题,当您在谷歌搜索有关突出显示文本区域中的单词时会发现该问题。

可以使用内置 API setSelectionRange 函数和 ::selection css 选择器在 textarea 元素中进行彩色选择。

注意,它一次只支持一个文本选择,并且只支持 textarea 获得焦点。

  const input = document
        .getElementById( 'text-box' );
  
  var i, l;

  input.focus();
  input.value = input.value.trim();
  
  i = input.value .indexOf( 'programming' );
  l = ( 'programming' ).length;
  
  // https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
  
  input
  .setSelectionRange( i, l + i );
::-moz-selection {
  background-color: yellow;
  color: red;
}
::selection {
  background-color: yellow;
  color: red;
}
<textarea id="text-box" size="40">
  I like programming with JavaScript!
</textarea>

答案 2 :(得分:1)

我无法对插入符号做些什么,所以我借用了其他人的工作,这使得代码有点庞大。我不知道它有多快,但效果很好:T

我借用的代码:

https://jsfiddle.net/nrx9yvw9/5/

Get a range's start and end offset's relative to its parent container

你可以在没有 jquery 的情况下运行:

 //(sorry for the grammer mistakes)

/*Caret function sources: https://jsfiddle.net/nrx9yvw9/5/ && https://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022*/
function createRange(e,t,n){if(n||((n=document.createRange()).selectNode(e),n.setStart(e,0)),0===t.count)n.setEnd(e,t.count);else if(e&&t.count>0)if(e.nodeType===Node.TEXT_NODE)e.textContent.length<t.count?t.count-=e.textContent.length:(n.setEnd(e,t.count),t.count=0);else for(var o=0;o<e.childNodes.length&&(n=createRange(e.childNodes[o],t,n),0!==t.count);o++);return n}function getCurrentCaretPosition(e){var t,n=0,o=e.ownerDocument||e.document,a=o.defaultView||o.parentWindow;if(void 0!==a.getSelection){if((t=a.getSelection()).rangeCount>0){var r=a.getSelection().getRangeAt(0),c=r.cloneRange();c.selectNodeContents(e),c.setEnd(r.endContainer,r.endOffset),n=c.toString().length}}else if((t=o.selection)&&"Control"!=t.type){var i=t.createRange(),g=o.body.createTextRange();g.moveToElementText(e),g.setEndPoint("EndToEnd",i),n=g.text.length}return n}function setCurrentCaretPosition(e,t){if(t>=0){var n=window.getSelection();range=createRange(e,{count:t}),range&&(range.collapse(!1),n.removeAllRanges(),n.addRange(range))}}
/*Caret functions end*/


/*
 * -> required | [...,...] -> example | {...} -> value type | || -> or 

  id:         Position of words for where they should be colored  [undefined,0,1,...] {int||string}
  color:      Color for words  [aqua,rgba(0,255,0,1),#ff25d0] {string}
  fontStyle:  Font style for words  [italic,oblique,normal] {string}
  decoration: Text decoration for words  [underlined,blink,dashes] {string}
* words:      Words that should be colored  {array}
*/
var keywords = [
   {
      color: "orange",
      words: [
         "SELECT",
         "FROM",
         "WHERE",
         "LIKE",
         "BETWEEN",
         "NOT",
         "FALSE",
         "NULL",
         "TRUE",
         "IN",
      ],
   },
   {
      id: 0,
      color: "red",
      fontStyle: "italic",
      decoration: "underline",
      words: ["TEST"],
   },
];

//defining node object as "editor"
var editor = document.getElementById("editor");

//listening editor for keyup event
editor.addEventListener("keyup", function (e) {
   // if ctrl or alt or shift or backspace and keyname's length is not 1, don't check
   if( e.ctrlKey || e.altKey || ( e.key.length - 1 && e.key != "Backspace" ) || ( e.shiftKey && e.char ) ) return;

   //getting caret position for applying it in the end, because after checking and coloring done; it's gonna be at the beginning.
   pos = getCurrentCaretPosition(this);

   
   text = this.innerText; //getting input's just text value
   words = text.split(/\s/gm); //splitting it from all whitespace characters

   for (var i = 0; i < keywords.length; i++)
      for (var n = 0; n < words.length; n++) {
         //looks for is word in our "keywords"' object and check's position if it's id entered
         if (keywords[i].words.indexOf(words[n].toUpperCase().trim()) > -1 && (keywords[i].id >= 0 ? keywords[i].id == n : true) )
            //applys options to word
            words[n] = `<span style="color:${ keywords[i].color ?? "white" };font-style:${ keywords[i].fontStyle ?? "normal" };text-decoration:${ keywords[i].decoration ?? "normal" }">${words[n]}</span>`;
      }

   //joining array elements with whitespace caracter and apply it to input
   this.innerHTML = words.join("&nbsp;");
   //restoring caret position
   setCurrentCaretPosition(this, pos);
});
    #editor {
   width: 400px;
   height: 100px;
   padding: 10px;
   background-color: #444;
   color: white;
   font-size: 14px;
   font-family: monospace;
   font-weight: normal;
   caret-color: white;
}
<div id="editor" spellcheck="false" contenteditable="true"></div>

答案 3 :(得分:0)

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

答案 4 :(得分:0)

使用Vanilla JS,您可以按照以下方式进行操作:

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

答案 5 :(得分:0)

您可以使用此代码

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