【问题标题】:Javascript: Change word colors depending on the word?Javascript:根据单词更改单词颜色?
【发布时间】:2018-09-22 04:23:51
【问题描述】:

抱歉,这个问题有点混乱。

我想根据单词是什么来改变句子中单词的背景颜色。

我希望用户能够像使用文本区域一样输入单词,但文本区域不支持单词背景颜色。

目前我只能想到这样的超级盗版解决方案:

var div = document.getElementById("div");

function highlight() {
  var words = div.textContent.split(" ");
  div.innerHTML = "";
  for (var i = 0; i < words.length; i++) {
    if (words[i] === "good") {
      div.innerHTML += "<span style=\"background-color: green;\">" + words[i] + "</span> ";
    } else if (words[i] === "bad") {
      div.innerHTML += "<span style=\"background-color: red;\">" + words[i] + "</span> ";
    } else {
      div.innerHTML += "<span>" + words[i] + "</span> ";
    }
  }
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(div.lastChild, 1);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
};
div.addEventListener("input", highlight);
highlight();
div {
  background-color: black;
  box-sizing: border-box;
  color: white;
  height: 128px;
  padding: 16px;
  width: 100%;
}
&lt;div id="div" contenteditable="true"&gt;good and bad colors&lt;/div&gt;

“好”这个词有绿色背景,“坏”这个词有一个红色背景。

但是,这是非常错误和可怕的,所以我希望有更好的方法来做到这一点。

任何帮助都会非常棒!

【问题讨论】:

    标签: javascript html css textarea background-color


    【解决方案1】:

    尝试使用数组方法,它们比for 循环更好用:

    const div = document.getElementById("div");
    function highlight() {
      const words = div.textContent.split(" ");
      div.innerHTML = "";
      words.forEach((word) => {
        const span = div.appendChild(document.createElement('span'));
        span.textContent = word + ' ';
        if (word === 'good') span.classList.add('green');
        if (word === 'bad') span.classList.add('red');
      });
    };
    div.addEventListener("blur", highlight);
    highlight();
    div {
      background-color: black;
      box-sizing: border-box;
      color: white;
      height: 128px;
      padding: 16px;
      width: 100%;
    }
    .green {
      background-color: green;
    }
    .red {
      background-color: red;
    }
    &lt;div id="div" contenteditable="true"&gt;good and bad colors&lt;/div&gt;

    【讨论】:

    • 谢谢你,但我真的只是在寻找更好的方法。我觉得使用 div 并以这种方式添加 span 是错误的,无论我是否使用数组方法。另外,使用我糟糕的方法,您必须手动将所选内容移动到文本的末尾,这样您就不会向后键入。
    • 使用直播contenteditable 非常痛苦——我根本不推荐它。考虑改用标准输入,带有结果元素或类似的东西。
    • 我可能最终会像您一样在模糊上添加颜色,但可以将其视为代码编辑器。变量以不同的颜色实时突出显示。虽然我很想添加结果元素,但我无法真正添加,因为它没有任何意义。
    • 您可以尝试使用带有事件监听器的 plain div。按下键时,更改与文本对应的变量,并相应地更新 div。按下箭头键时,相应地增加/减少索引(当前文本光标位置)。在每次索引更改(或添加/删除新字母)时,重新计算文本光标的位置,并以某种方式使其在 div 中的适当位置可见。
    猜你喜欢
    • 2023-01-12
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    相关资源
    最近更新 更多