IE <= 8 equivalent to selection.getRangeAt()?

2019-07-07 00:23发布

问题:

I need to get the range object of the current selection. The following works in most browsers:

 range = selection.getRangeAt(0);

Is there an equivalent native JavaScript command for IE7/8 ?

回答1:

Sort of. IE <= 8 has selection and range functionality but it's very different to other browsers. The nearest equivalent is:

var range = document.selection.createRange();

... which will (usually) create you a proprietary TextRange object representing the selected content.

At the risk of promoting my own stuff, you may be interested in my Rangy library, which provides a DOM Range and Selection API in all major browsers, in particular IE <= 8.