Javascript 更改 textarea 中特定单词的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37139076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:58:42  来源:igfitidea点击:

Change color of specific words in textarea

javascriptjqueryhtmlonkeyup

提问by Mohammad

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.

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

I've searched around a bit and beyond this (https://jsfiddle.net/qcykvr8j/2/) I unfortunately do not come any further.

我已经搜索了一些并且超出了这个范围(https://jsfiddle.net/qcykvr8j/2/)我很遗憾没有再进一步。

Example code

示例代码

HTML:

HTML:

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

JS:

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:

JSFiddle:

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

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

But this example deletes the color when I type further.

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

What I want is this:

我想要的是这个:

Right way

正确的方法

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

我已经尝试过将 Keyup 与 jQuery 中的 Contains 结合使用,但这并没有产生太大的效果。

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

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

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

包含: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

问候, 延斯

回答by Mohammad

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

你不能改变的话中的颜色<textarea>,但你可以使用contenteditable属性来进行<div><span><p>看起来像一个<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.

为此,您可以使用 JavaScript 插件,但如果您想创建一个新插件,下面的代码可能会对您有所帮助。

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

为此,您需要获取文本中的任何单词。然后检查它是否是 SQL 关键字。

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

回答by prtk712

JS FIDDLE CODE

JS小提琴代码

HTML-

HTML-

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

CSS-

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 -

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