Mark.js contenteditable - 运行 输入标记

Mark.js contenteditable - run Mark on input

我正在用 contenteditable div 制作一个“单词检查器”,同时使用 mark.js 来突出某些 words/word 组。

我遇到的问题是我无法找到“运行”Mark.js 的方法,因为正在输入 (copy/pasted) 中的单词。

我试图通过向文本区域添加事件侦听器来实现此目的,但这会引发错误:mark is not defined. textarea.addEventListener("input", mark); 并通过更改 mark实例 textarea.addEventListener("input", instance); 给我一个错误:TypeError: 属性 'handleEvent' is not callable.Here is the fiddle.

我还查看了在 SO 和 google 上找到的各种示例,但我似乎无法找到我要找的东西。我找到的最接近的是 , but I still couldn't get it to work.

如有任何帮助,我们将不胜感激。如果我可以提供任何其他信息,请告诉我。

var textarea = document.getElementById("textarea");
var instance = new Mark("div.textarea");

var red   = ["red", "blood"];
var brown = ["brown", "pudding"];
var green = ["green", "grass"];

instance.mark(red, {
   seperateWordSearch: false,
   className: "red",
   "accuracy": {
      "value": "exactly",
      "limiters": [",", ".", "!", "?"]
   }
});


instance.mark(brown, {
   seperateWordSearch: false,
   className: "brown",
   "accuracy": {
      "value": "exactly",
      "limiters": [",", ".", "!", "?"]
   }
});

instance.mark(green, {
   seperateWordSearch: false,
   className: "green",
   "accuracy": {
      "value": "exactly",
      "limiters": [",", ".", "!", "?"]
   }
});

textarea.addEventListener("input", mark);
.red {
    background-color: lightcoral;
}

.green{
    background-color: lightgreen;
}

.brown{
    background-color: burlywood;
}
<h2>Text checker</h2>
<div class="textarea" id="textarea" contenteditable="true">
   I hate blood pudding and so do you.
</div>

您可以将所有 instance.mark(...) 调用放在一个单独的函数中(例如 markWords)。 然后您可以在输入文本更改时调用该函数:

var textarea = document.getElementById("textarea");
var instance = new Mark("div.textarea");

var red   = ["red", "blood"];
var brown = ["brown", "pudding"];
var green = ["green", "grass"];

//create a function which will highlight all specified words
var markWords = function() {
  instance.mark(red, {
     seperateWordSearch: false,
     className: "red",
     "accuracy": {
        "value": "exactly",
        "limiters": [",", ".", "!", "?"]
     }
  });


  instance.mark(brown, {
     seperateWordSearch: false,
     className: "brown",
     "accuracy": {
        "value": "exactly",
        "limiters": [",", ".", "!", "?"]
     }
  });

  instance.mark(green, {
     seperateWordSearch: false,
     className: "green",
     "accuracy": {
        "value": "exactly",
        "limiters": [",", ".", "!", "?"]
     }
  });
}

//call the markWords function to do the initial highlighting
markWords();

//setup listener to call function markWords
textarea.addEventListener("input", markWords);