execCommand insertHTML中断存储的window.getSelection() [英] execCommand insertHTML breaks stored window.getSelection()

查看:130
本文介绍了execCommand insertHTML中断存储的window.getSelection()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用选择文本和恢复页面中所选文本的方法时,我发现在两者之间运行execCommand('insertHTML...会导致存储的选择中断.

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)

这很好用,但是一旦您运行execCommand('insertHTML..,选择endOffset会将其自身设置为与选择startOffset

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?

完整的错误示例,带有一些基本的控制台日志记录,可以在这里看到. http://jsfiddle.net/blowsie/Y8pJ7/

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.

推荐答案

如何最好地保存和还原选择内容取决于您的工作.对于您的特定示例,在现有文本仅进行大小写转换的情况下,我建议使用基于字符索引的方法,例如 https://stackoverflow.com/a/5596688/96100 (尽管该答案需要Rangy,但可以更改为不要求它: http://jsfiddle.net/Y8pJ7/8 ).

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

对于其他一些情况,更好的方法是在选择的开始和结尾使用不可见的标记元素,这是的rangy/wiki/SelectionSaveRestoreModule"rel =" nofollow noreferrer>选择保存/恢复模块 Rangy (披露:我是Rangy的作者).

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

2012年6月18日更新

Rangy现在可以通过新的基于字符偏移的选择和范围保存和恢复. TextRange模块(演示).

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

这篇关于execCommand insertHTML中断存储的window.getSelection()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆