我正在使用剑道 UI 编辑器。我想突出显示在编辑器中输入/粘贴的多余字符。这就是我所做的:
$(function () {
var $editor = $('#txt-editor');
$editor.kendoEditor({
keydown: ValidateRichTextEditor
});
});
function ValidateRichTextEditor(e) {
var editor = $(e.sender.textarea),
kendoEditor = editor.data('kendoEditor'),
characters = kendoEditor.body.innerText.length,
limit = editor.data('valLengthMax');
if (characters > limit) {
var textNodes = getTextNodes(kendoEditor.body),
charCount = 0,
startNode, startOffset;
for (var i = 0, textNode; textNode = textNodes[i++];) {
var chars = charCount + textNode.length;
if (limit < chars) {
//set the text node as the starting node
//if the characters hit the limit set
startNode = textNode;
startOffset = chars - charCount;
break;
}
//add the length of the text node to the current character count
charCount += textNode.length;
}
var range = kendoEditor.createRange();
range.setStart(startNode, startOffset);
kendoEditor.selectRange(range);
kendoEditor.document.execCommand('backColor', false, '#fcc');
}
}
function getTextNodes(node) {
var textNodes = [];
//node type 3 is a text node
if (node.nodeType == 3) {
textNodes.push(node);
} else {
var children = node.childNodes;
for (var i = 0, len = children.length; i < len; i++) {
textNodes.push.apply(textNodes, getTextNodes(children[i]));
}
}
return textNodes;
}
到目前为止,突出显示有效,但光标位置始终位于突出显示开始的位置。如何定位光标以便它记住它的最后位置?比如说我只是继续打字,光标应该在编辑器内容的末尾。或者当我单击内容中间的某个位置时,光标应该从我单击内容的位置开始。
对此的帮助将不胜感激。谢谢!