execCommand insertHTML breaks stored window.getSelection()

江枫思渺然 提交于 2019-11-27 09:52:18
Tim Down

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).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!