gpt4 book ai didi

javascript - 如何更改文本区域中文本的颜色

转载 作者:行者123 更新时间:2023-11-30 11:04:48 25 4
gpt4 key购买 nike

我有一个 textarea,当我输入内容时,某些单词的颜色应该会改变。

例如,如果键入的文本是下一个:他去市场买了一个苹果

  1. “市场”这个词应该变成绿色
  2. “苹果”这个词应该变成红色

这是我当前的代码:

var str = 'market';
var value = str.includes('market');

if (value == str) {
document.getElementById("text").style.color = "green";
} else {
document.getElementById("text").style.color = "red";
}
<textarea rows="9" cols="100" id="text" onClick="changeText();"></textarea>

最佳答案

很遗憾,您不能在 textarea 中添加标记, 但这里有一个你可以作为起始方法的想法,它来自这个 link .该方法将基于此:

The basic idea is to carefully position a <div> behind the <textarea>. Then JavaScript will be used to copy any text entered into the <textarea> to the <div>. A bit more JavaScript will make that both elements scroll as one. With everything perfectly aligned, we can add markup inside the <div> to give colors to some particular words, and we going to set text color to transparent on the <textarea>, completing the illusion.

基本实现:

// Initialization.

const colorMap = {"apple": "red", "market": "green", "banana": "orange"};
let textArea = document.getElementById("myTextArea");
let customArea = document.querySelector(".custom-area");
let backdrop = document.querySelector(".backdrop");

// Event listeners.

textArea.addEventListener("input", function()
{
customArea.innerHTML = applyColors(textArea.value);
});

textArea.addEventListener("scroll", function()
{
backdrop.scrollTop = textArea.scrollTop;
});

function applyColors(text)
{
let re = new RegExp(Object.keys(colorMap).join("|"), "gi");

return text.replace(re, function(m)
{
let c = colorMap[m.toLowerCase()];
return `<spam style="color:${c}">${m}</spam>`;
});
}
.backdrop, #myTextArea {
font: 12px 'Open Sans', sans-serif;
letter-spacing: 1px;
width: 300px;
height: 100px;
}

#myTextArea {
margin: 0;
position: absolute;
border-radius: 0;
background-color: transparent;
color: transparent;
caret-color: #555555;
z-index: 2;
resize: none;
}

.backdrop {
position: absolute;
z-index: 1;
border: 2px solid transparent;
overflow: auto;
pointer-events: none;
}

.custom-area {
white-space: pre-wrap;
word-wrap: break-word;
}
<div class="container">
<div class="backdrop">
<div class="custom-area">
<!-- Cloned text with colors will go here -->
</div>
</div>
<textarea id="myTextArea"></textarea>
</div>

请注意,这只是理解基本思想的基本方法。但是通过一些工作,也许你可以获得一个通用版本。例如,到现在为止,textarea无法调整大小。但也许您可以检测到该事件并重新调整 backdrop动态地。

关于javascript - 如何更改文本区域中文本的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56086994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com