简体   繁体   English

IE选择和范围问题

[英]Issue with IE Selection and Range

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: 我试图获取每个选择的开始元素和结束元素以及每个选择的偏移量,我在Firefox中按如下方式进行操作:

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? 但是我不知道如何在IE6中做到这一点,任何人都可以指出正确的方向吗?

document.selection. 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. 但是,IE返回的TextRange对象与Firefox / WebKit / W3不匹配,确定起点和终点的确切位置非常令人沮丧。 Depending on what exactly you are doing with the range you may be able to get somewhere with range.parentElement(), range.inRange() or range.compareEndPoints(). 根据您对范围所做的确切操作,您可以使用range.parentElement(),range.inRange()或range.compareEndPoints()到达某个地方。 For rich text editors you will usually end up using the staggeringly ugly range.execCommand() interface. 对于富文本编辑器,您通常最终会使用非常丑陋的range.execCommand()接口。

The IE Range implementation is so odd and different to the Mozilla/Webkit/W3 model that you typically end up with completely different code paths for everything to do with selections between the two. IE Range的实现是如此奇怪,并且与Mozilla / Webkit / W3模型不同,以至于通常情况下,与两者之间的选择有关的所有事情的代码路径都完全不同。

If you know the object the selection is in (eg, 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();
    }
}

You should look at the ControlRange and TextRange objects of the IE BOM. 您应该查看IE BOM的ControlRangeTextRange对象。

AnchorOffset,focusOffset and window.getSelection() are not supported by IE6/7 I believe. 我相信IE6 / 7不支持AnchorOffset,focusOffset和window.getSelection()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM