当文本区域包含来自数组的特定单词时更改背景颜色



如果textArea包含的goodWords多于badWords,我想将文档的背景颜色更改为goodColor。反之亦然。此外,如果从数组中输入相同的单词两次,我需要将其计数为包含两次。

const goodWords = ['happy', 'joyful', 'amazing', 
'enjoyed', 'fun', 'excited', 'nice', 'funny', 
'fantastic', 'good', 'calm', 'comfortable', 
'glad', 'confident', 'kind'];
const badWords = ['angry', 'sad', 'upset', 
'defeated', 'embarrassed', 'jealous', 'nervous', 
'anxious', 'unhappy', 'miserable', 'worst', 
'bad'];
const goodColor = 'rgb(225,225,56,20)'
const badColor = 'rgb(100,100,50,50)'
textArea.addEventListener('input', function () {
for (let good of goodWords) {
if(text.value.includes(good)) {
document.body.style.backgroundColor = 
goodColor;

}  
}
for(let bad of badWords) {
if (text.value.includes(bad)) {

document.body.style.backgroundColor = badColor;
}
}
})

首先,您需要将textarea值按单词分隔,然后计算两个数组中的所有匹配项。然后,您可以简单地比较它们并根据自己的意愿为bg上色。

const goodWords = ['happy', 'joyful', 'amazing', 
'enjoyed', 'fun', 'excited', 'nice', 'funny', 
'fantastic', 'good', 'calm', 'comfortable', 
'glad', 'confident', 'kind'];
const badWords = ['angry', 'sad', 'upset', 
'defeated', 'embarrassed', 'jealous', 'nervous', 
'anxious', 'unhappy', 'miserable', 'worst', 
'bad'];
const goodColor = 'rgb(225,225,56,20)'
const badColor = 'rgb(100,100,50,50)'
textArea.addEventListener('input', function () {
// Exit if textarea contains only spaces or empty
if (text.value.trim().length === 0) {
return;
}
// Using regexp break value to array of words
const words = text.value.match(/b(w+)b/g)
let goodCount = 0;
let badCount = 0;
// Cycle through words
for (let i = 0; i < words.length - 1; i++) {
if (goodWords.includes(words[i])) {
goodCount++;
}
if (badWords.includes(words[i])) {
badCount++;
}
}
if (goodCount > badCount) {
document.body.style.backgroundColor = goodColor;
} else if (goodCount < badCount) {
document.body.style.backgroundColor = badColor;
} else {
// Some neutral color
}
})

最新更新