Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

javascript - What's the best way to set cursor/caret position?

If I'm inserting content into a textarea that TinyMCE has co-opted, what's the best way to set the position of the cursor/caret?

I'm using tinyMCE.execCommand("mceInsertRawHTML", false, content); to insert the content, and I'd like set the cursor position to the end of the content.

Both document.selection and myField.selectionStart won't work for this, and I feel as though this is going to be supported by TinyMCE (through something I can't find on their forum) or it's going to be a really ugly hack.

Later: It gets better; I just figured out that, when you load TinyMCE in WordPress, it loads the entire editor in an embedded iframe.

Later (2): I can use document.getElementById('content_ifr').contentDocument.getSelection(); to get the selection as a string, but not a Selection Object that I can use getRangeAt(0) on. Making progress little by little.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First what you should do is add a span at the end of the content you want to create.

var ed = tinyMCE.activeEditor;

//add an empty span with a unique id
var endId = tinymce.DOM.uniqueId();
ed.dom.add(ed.getBody(), 'span', {'id': endId}, '');

//select that span
var newNode = ed.dom.select('span#' + endId);
ed.selection.select(newNode[0]);

This is a strategy used by the TinyMCE developers themselves in writing Selection.js. Reading the underlying source can be massively helpful for this kind of problem.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...