是否有任何支持获取和设置光标位置的 javascript 富文本编辑器?
user1022241
问问题
4015 次
3 回答
1
我不会解释可怕的细节,但这会起作用:
function getTextNodesIn(node) {
var textNodes = [];
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, getTextNodesIn(children[i]));
}
}
return textNodes;
}
function setSelectionRange(el, start, end) {
if (document.createRange && window.getSelection) {
var range = document.createRange();
range.selectNodeContents(el);
var textNodes = getTextNodesIn(el);
var foundStart = false;
var charCount = 0, endCharCount;
for (var i = 0, textNode; textNode = textNodes[i++]; ) {
endCharCount = charCount + textNode.length;
if (!foundStart && start >= charCount && (start < endCharCount || (start == endCharCount && i < textNodes.length))) {
range.setStart(textNode, start - charCount);
foundStart = true;
}
if (foundStart && end <= endCharCount) {
range.setEnd(textNode, end - charCount);
break;
}
charCount = endCharCount;
}
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (document.selection && document.body.createTextRange) {
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(true);
textRange.moveEnd('character', end);
textRange.moveStart('character', start);
textRange.select();
}
}
现在您只需获取元素并选择内容:
setSelectionRange(document.getElementById('dijitEditorBody'), 10, 50);
于 2011-11-15T05:39:17.120 回答
0
是的,redactor.js正在这样做:
$('#redactor').redactor('setCaret', element, 4);
于 2013-06-20T16:08:20.707 回答
0
我正在寻找 dijit.Editor 的解决方案,并遇到了这个老问题。这是我这样做的方式(这是对 dijit/_editor/EnterKeyHandling 插件的剽窃)。
我创建了自己的插件,如下所示:
define([
"dojo/_base/declare",
"dijit/_editor/_Plugin",
"dijit/_editor/range",
"dijit/_editor/selection"
], function(declare, _Plugin, rangeapi, selectionapi) {
var MyPlugin = declare(_Plugin, {
setToolbar: function(editorToolbar){
// [...]
this.own(this.editor.on('keypressed', lang.hitch(this, 'onKeyPressed')));
},
onKeyPressed: function(){
// summary:
// Handler for after the user has pressed a key, and the display has been updated.
var block = undefined,
blockNode = undefined,
selection = rangeapi.getSelection(this.editor.window),
range = selection.getRangeAt(0);
if(!range.collapsed){
range.deleteContents();
selection = rangeapi.getSelection(this.editor.window);
range = selection.getRangeAt(0);
}
block = rangeapi.getBlockAncestor(range.endContainer, null, this.editor.editNode);
if (block.blockNode) {
blockNode = block.blockNode;
// this is the node under the cursor...
console.debug(blockNode);
}
});
_Plugin.registry["myplugin"] = _Plugin.registry["myplugin"] = function(args){
return new MyPlugin();
};
return MyPlugin;
});
然后只需将“myplugin”添加到您的 dijit/Editor 的“extraPlugins”属性中。
于 2014-06-18T14:37:13.873 回答