Create TextSelection from selection in IE11

本秂侑毒 提交于 2019-12-18 17:12:08

问题


I am trying to fix an application in IE11 and I stuck in this bug: In the older version of IE ther was a simple selection object but it is deprecated in IE11. The MSDN page offer to use getSelection instead of that, but it is not the same. I need to create a TextRange based on the selection and in the old API there was a simple solution:

// there is a TextRange object what I need
var textRange = document.selection.createRange();

The new HTMLSelection object has no createRange() method and I didn't find any proper solution, what is not modify the DOM.

I try this: http://jsfiddle.net/p4Lu4/1/ (Usage: Select some text and hit any key. )

The problem with it: If you select throw one of the red boxes, it will remove the box.

Can anyone know a better solution?

Solution:

I think, I found a solution. Not the best and nicest but it is working for me: I can create the exact same TextRange from Selection.

http://jsfiddle.net/p4Lu4/4/

Update 2:

I create a modul for this: https://gist.github.com/festo/50fe800c7369db140a62


回答1:


My Rangy library has code to convert a DOM-compatible range to an IE TextRange as part of providing DOM range and selection support in IE <= 8. The latest build exposes this conversion explicitly on the selection object:

var textRange = rangy.getSelection().getNativeTextRange();

Note that the getNativeTextRange() method of a Rangy selection only exists in IE.

Another alternative is to use Rangy's TextRange module, which among other things adds an IE-like findText() method to Rangy's range object, along with the class applier module to do the highlighting. This will work in all major browsers.

Demo: http://jsfiddle.net/sycqeev2/

I'm not sure what's supposed to happen in your demo when you highlight text and press a key, so I haven't attempted to do anything with that.



来源:https://stackoverflow.com/questions/24958043/create-textselection-from-selection-in-ie11

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