最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Issue with IE Selection and Range - Stack Overflow

programmeradmin3浏览0评论

I'm trying to get the start element and the end element of a selection and the offset of the selection in each, i do this in firefox as follows:

var delselection = window.getSelection();

var startOffset = delselection.anchorOffset;

var endOffset = delselection.focusOffset;

var startNode = delselection.anchorNode.parentNode;

var endNode = delselection.focusNode.parentNode;

However i have no idea how to do this in IE6, anyone able to point me in the right direction?

I'm trying to get the start element and the end element of a selection and the offset of the selection in each, i do this in firefox as follows:

var delselection = window.getSelection();

var startOffset = delselection.anchorOffset;

var endOffset = delselection.focusOffset;

var startNode = delselection.anchorNode.parentNode;

var endNode = delselection.focusNode.parentNode;

However i have no idea how to do this in IE6, anyone able to point me in the right direction?

Share Improve this question edited Dec 27, 2012 at 17:01 Igor 34.1k14 gold badges82 silver badges116 bronze badges asked Oct 20, 2008 at 10:55 user11198user11198 1312 silver badges6 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

document.selection.

However the TextRange object returned by IE does not match Firefox/WebKit/W3's, and determining the exact positions of the start and end points is very frustrating. Depending on what exactly you are doing with the range you may be able to get somewhere with range.parentElement(), range.inRange() or range.pareEndPoints(). For rich text editors you will usually end up using the staggeringly ugly range.execCommand() interface.

The IE Range implementation is so odd and different to the Mozilla/Webkit/W3 model that you typically end up with pletely different code paths for everything to do with selections between the two.

You should look at the ControlRange and TextRange objects of the IE BOM.

AnchorOffset,focusOffset and window.getSelection() are not supported by IE6/7 I believe.

If you know the object the selection is in (e.g., it's an input field the user is typing in that you want to change while they're typing), this code does the trick:

var selObj = null;
var selSave = null;
var selSaveEnd = null;

function SaveSelection(obj) {
    if (obj.selectionStart) {
        selObj = obj;
        selSave = obj.selectionStart;
        selSaveEnd = obj.selectionEnd;
    }
    else {
        // Internet Explorer case
        selSave = document.selection.createRange();
    }
}

function RestoreSelection() {
    if (selObj) {
        selObj.focus();
        selObj.selectionStart = selSave;
        selObj.selectionEnd = selSaveEnd;
    }
    else {
        // Internet Explorer case
        selSave.select();
    }
}
发布评论

评论列表(0)

  1. 暂无评论