execCommand insertHTML breaks stored window.getSel

2019-01-09 19:44发布

When using methods of selecting text and restoring selected text in a page, I have found that running execCommand('insertHTML... inbetween causes the stored selection to break.

This is a sample of how the text is selected and restored.

// Get Selection
 var sel = window.getSelection().getRangeAt(0);
 // Clear Selections 
 window.getSelection().removeAllRanges();
 // Restore Selection 
 window.getSelection().addRange(sel)

This works fine, however once you run execCommand('insertHTML.. the selections endOffset sets itself to the same value as the selections startOffset

Is there a reason for this? More importantly is there a way round this?


A full example of the bug, complete with some basic console logging can be seen here. http://jsfiddle.net/blowsie/Y8pJ7/

The objective of this fiddle is to select text , transform it to uppercase and then reselect the text.

1条回答
淡お忘
2楼-- · 2019-01-09 20:11

How best to save and restore the selection really depends on what you're doing. For your specific example, where existing text is just having its case transformed, I'd suggest a character index-based approach, such as https://stackoverflow.com/a/5596688/96100 (although that answer requires Rangy, but can be trivially changed not to require it: http://jsfiddle.net/Y8pJ7/8).

For some other cases, a better approach is to use invisible marker elements at the start and end of the selection, which is the approach taken by the selection save/restore module of Rangy (disclosure: I am Rangy's author).

UPDATE 18 June 2012

Rangy now has character offset-based save and restore of selections and ranges via a new TextRange module (demo).

查看更多
登录 后发表回答