简体   繁体   中英

How do you move the caret to a specific character offset inside a conteneditable element

I am using this to retrieve the count

var window.getSelection().getRangeAt(0).startOffset;

and this is what I have so far to restore the count.

var range = window.getSelection().getRangeAt(0);
range.setStart(dNode, dc);
range.insertNode (mcmsfinalLinkhandle);

I am using localStorage to hold the count. This may seem tedious but I appreciate any help. This should be an entry level javascript issue so I feel I should be able to do this without convoluted solution. So far all I am lacking is the ability to place by character instead of by node or line and to keep the caret at the point of insert. Thx again for any help.

The answer, unfortunately, is - it depends on the browser. I believe FF, Chrome and Safari use the same interface - research it more here: https://developer.mozilla.org/en/DOM/Range

IE and I think Opera, use a different interface: http://msdn.microsoft.com/en-us/library/ie/ms535872(v=vs.85).aspx

Word of advice: if you can, try to stay away from this. Either use an off-the-shelf RTE editor or just a regular text area.

You have to create a range with document.createRange , move it to the correct location, and then select it.

Here's a great solution https://stackoverflow.com/a/3866442/1450483

First, there are separate Range and Selection APIs. A Range is just a single continuous chunk of a document and is not necessarily tied to a selection. Browsers vary as to whether changing a range obtained from the selection affects the selection (Firefox does, others don't), so to be certain of updating the selection, you need to remove and add the range:

var sel = window.getSelection();
var range = sel.getRangeAt(0);
range.setStart(dNode, dc);
range.insertNode(mcmsfinalLinkhandle);
sel.removeAllRanges();
sel.addRange(range);

Moving the caret to a specific character offset within the visible text of an editable element is non-trivial and the code to achieve it far from entry level because everything in the DOM Range API revolves around nodes rather than text, and determining the text being edited requires computing various CSS properties ( display , white-space , visibility , to name a few).

You can use my Rangy library and its new TextRange module ( demo ) to work with the caret and selection as character offsets.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM