快速更新TinyMCE中句子的亮点

时间:2016-11-19 00:02:56

标签: javascript jquery

好。我用Markjs.io和TinyMCE创建了一个突出长句的小工具(超过n个单词)。

我目前正在加载时正确突出显示文字。

然后我尝试添加som .on('keyup',function())和.on('change',function())来运行函数并在我输入时重新计算高光/标记。

然而。这种方法显然不断返回原始文本。而且我无法在该字段中添加任何新文本。

我想做什么:

所以我想做的是弄清楚我的函数应该如何运行以不断重新计算并突出显示长句。但在某种程度上,它实际上也添加了我在TinyMCE编辑器中输入的新文本或当前编辑。

在CodePen上提供:http://codepen.io/MarkBuskbjerg/pen/rWWRbX

HTML:

<div id="myTextArea" contenteditable="true">
    Any text will do. Above 16 words in a single sentence - from dot to dot - will be highlightet for all the world to see.
</div>

JavaScript(jQuery):

tinymce.init({
  selector: '#myTextArea',
  height: 300,
  setup: function(ed) {
    ed.on('change', myCustomInitInstance);
    ed.on('keyup', myCustomInitInstance);
    ed.on('paste', myCustomInitInstance);
    ed.on('cut', myCustomInitInstance);
  },
  init_instance_callback: "myCustomInitInstance",
});

function myCustomInitInstance(inst) {
  var rawText = tinyMCE.get('myTextArea').getContent({
    format: 'text'
  });

  var sentenceArray = rawText.split(".");
  var matchWarning = [];
  var longSentence = 16;
  var words;
  var wordCounter;
  var output;

  for (var i in sentenceArray) {
    words = sentenceArray[i].split(" ");
    wordCounter = words.length;
    if (wordCounter > longSentence) {
      matchWarning.push(sentenceArray[i]);
    }
  }

  var $clone = $("#myTextArea").clone();
  $clone.mark(matchWarning, {
    "separateWordSearch": false,
  });

  tinyMCE.activeEditor.setContent($clone.html());
}):

1 个答案:

答案 0 :(得分:1)

问题在于:

var $clone = $("#myTextArea").clone();

每次只从textarea获取原始值,这就是为什么它没有更新。

在WYSIWYG iframe的body元素上使用makejs应该可以工作:

function myCustomInitInstance(inst) {
  var rawText = tinyMCE.get('myTextArea').getContent({
    format: 'text'
  });

  var sentenceArray = rawText.split(".");
  var matchWarning = [];
  var longSentence = 16;
  var words;
  var wordCounter;
  var output;

  for (var i in sentenceArray) {
    words = sentenceArray[i].split(" ");
    wordCounter = words.length;
    if (wordCounter > longSentence) {
      matchWarning.push(sentenceArray[i]);
    }
  }

  var editor = tinyMCE.activeEditor;
  // Store the selection
  var bookmark = editor.selection.getBookmark();

  // Remove previous marks and add new ones
  $(editor.getBody()).unmark().mark(matchWarning, {
    acrossElements: true,
    "separateWordSearch": false,
  });

  // Restore the selection
  editor.selection.moveToBookmark(bookmark);
}