IE的document.selection.createRange不包括前导或尾随空行

时间:2010-09-01 23:26:14

标签: javascript internet-explorer dom

我正在尝试从textarea中提取确切的选择和光标位置。像往常一样,大多数浏览器中的简单操作都不在IE中。

我正在使用它:

var sel=document.selection.createRange();
var temp=sel.duplicate();
temp.moveToElementText(textarea);
temp.setEndPoint("EndToEnd", sel);
selectionEnd = temp.text.length;
selectionStart = selectionEnd - sel.text.length;

99%的时间都有效。问题是TextRange.text不会返回前导或尾随换行符。因此,当光标在段落之后是几个空行时,它会在前一段的末尾产生一个位置 - 而不是实际的光标位置。

例如:

the quick brown fox|    <- above code thinks the cursor is here

|    <- when really it's here

我能想到的唯一修复是在选择之前和之后临时插入一个字符,抓取实际选择,然后再次删除那些临时字符。这是一个黑客,但在快速实验中看起来它会起作用。

但首先我要确定没有更简单的方法。

4 个答案:

答案 0 :(得分:12)

我正在添加另一个答案,因为我之前的答案已经有点史诗了。

这是我认为最好的版本:它需要bobince的方法(在我的第一个答案的评论中提到)并修复了我不喜欢它的两件事,首先它依赖于错误的TextRanges在textarea之外(从而损害性能),以及为了移动范围边界而必须为字符数选择一个巨大数字的肮脏。

function getSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }

    return {
        start: start,
        end: end
    };
}

var el = document.getElementById("your_textarea");
var sel = getSelection(el);
alert(sel.start + ", " + sel.end);

答案 1 :(得分:1)

<强> N.B。请参阅我的other answer以获取我能提供的最佳解决方案。我要留下这里作为背景。

我遇到过这个问题,并编写了适用于所有情况的以下内容。在IE中,它确实使用您建议的方法在选择边界临时插入一个字符,然后使用document.execCommand("undo")删除插入的字符并防止插入保留在撤消堆栈中。我很确定没有更简单的方法。令人高兴的是,IE 9将支持selectionStartselectionEnd属性。

function getSelectionBoundary(el, isStart) {
    var property = isStart ? "selectionStart" : "selectionEnd";
    var originalValue, textInputRange, precedingRange, pos, bookmark;

    if (typeof el[property] == "number") {
        return el[property];
    } else if (document.selection && document.selection.createRange) {
        el.focus();
        var range = document.selection.createRange();

        if (range) {
            range.collapse(!!isStart);

            originalValue = el.value;
            textInputRange = el.createTextRange();
            precedingRange = textInputRange.duplicate();
            pos = 0;

            if (originalValue.indexOf("\r\n") > -1) {
                // Trickier case where input value contains line breaks

                // Insert a character in the text input range and use that as
                // a marker
                range.text = " ";
                bookmark = range.getBookmark();
                textInputRange.moveToBookmark(bookmark);
                precedingRange.setEndPoint("EndToStart", textInputRange);
                pos = precedingRange.text.length - 1;

                // Executing an undo command to delete the character inserted
                // prevents this method adding to the undo stack. This trick
                // came from a user called Trenda on MSDN:
                // http://msdn.microsoft.com/en-us/library/ms534676%28VS.85%29.aspx
                document.execCommand("undo");
            } else {
                // Easier case where input value contains no line breaks
                bookmark = range.getBookmark();
                textInputRange.moveToBookmark(bookmark);
                precedingRange.setEndPoint("EndToStart", textInputRange);
                pos = precedingRange.text.length;
            }
            return pos;
        }
    }
    return 0;
}

var el = document.getElementById("your_textarea");
var startPos = getSelectionBoundary(el, true);
var endPos = getSelectionBoundary(el, false);
alert(startPos + ", " + endPos);

<强>更新

根据bobince在评论中建议的方法,我创建了以下内容,这似乎运作良好。一些说明:

  1. bobince的方法更简单,更短。
  2. 我的方法是侵入性的:它会在还原这些更改之前更改输入的值,尽管没有明显的效果。
  3. 我的方法的优点是可以将所有操作保留在输入中。 bobince的方法依赖于创建从正文开始到当前选择的范围。
  4. 3.的结果是,bobince的性能随着文档中输入的位置而变化,而我的则不然。我的简单测试表明,当输入接近文档的开头时,bobince的方法明显更快。当输入在大量HTML之后,我的方法更快。

  5. function getSelection(el) {
        var start = 0, end = 0, normalizedValue, textInputRange, elStart;
        var range = document.selection.createRange();
        var bigNum = -1e8;
    
        if (range && range.parentElement() == el) {
            normalizedValue = el.value.replace(/\r\n/g, "\n");
    
            start = -range.moveStart("character", bigNum);
            end = -range.moveEnd("character", bigNum);
    
            textInputRange = el.createTextRange();
            range.moveToBookmark(textInputRange.getBookmark());
            elStart = range.moveStart("character", bigNum);
    
            // Adjust the position to be relative to the start of the input
            start += elStart;
            end += elStart;
    
            // Correct for line breaks so that offsets are relative to the
            // actual value of the input
            start += normalizedValue.slice(0, start).split("\n").length - 1;
            end += normalizedValue.slice(0, end).split("\n").length - 1;
        }
        return {
            start: start,
            end: end
        };
    }
    
    var el = document.getElementById("your_textarea");
    var sel = getSelection(el);
    alert(sel.start + ", " + sel.end);
    

答案 2 :(得分:1)

负数百万美元的举动似乎完美无缺。

这是我最终的结果:

var sel=document.selection.createRange();
var temp=sel.duplicate();
temp.moveToElementText(textarea);
var basepos=-temp.moveStart('character', -10000000);

this.m_selectionStart = -sel.moveStart('character', -10000000)-basepos;
this.m_selectionEnd = -sel.moveEnd('character', -10000000)-basepos;
this.m_text=textarea.value.replace(/\r\n/gm,"\n");

谢谢bobince - 当它只是一个评论时,我怎么能把你的答案投票:(

答案 3 :(得分:1)

一个jquery插件,用于在文本区域中获取选择索引的开始和结束。上面的javascript代码对IE7和IE8没有用,并且给出了非常不一致的结果,所以我编写了这个小的jquery插件。允许临时保存选择的开始和结束索引,并在以后高亮显示选择。

这里有一个工作示例和简要版本:http://jsfiddle.net/hYuzk/3/

带有评论等的更多详细信息版本在此处:http://jsfiddle.net/hYuzk/4/

        // Cross browser plugins to set or get selection/caret position in textarea, input fields etc for IE7,IE8,IE9, FF, Chrome, Safari etc 
        $.fn.extend({ 
            // Gets or sets a selection or caret position in textarea, input field etc. 
            // Usage Example: select text from index 2 to 5 --> $('#myTextArea').caretSelection({start: 2, end: 5}); 
            //                get selected text or caret position --> $('#myTextArea').caretSelection(); 
            //                if start and end positions are the same, caret position will be set instead o fmaking a selection 
            caretSelection : function(options) 
            { 
            if(options && !isNaN(options.start) && !isNaN(options.end)) 
            { 
            this.setCaretSelection(options); 
            } 
            else 
            { 
            return this.getCaretSelection(); 
            } 
            }, 
            setCaretSelection : function(options) 
            { 
            var inp = this[0]; 
            if(inp.createTextRange) 
            { 
            var selRange = inp.createTextRange(); 
            selRange.collapse(true); 
            selRange.moveStart('character', options.start); 
            selRange.moveEnd('character',options.end - options.start); 
            selRange.select(); 
            } 
            else if(inp.setSelectionRange) 
            { 
            inp.focus(); 
            inp.setSelectionRange(options.start, options.end); 
            } 
            }, 
            getCaretSelection: function() 
            { 
            var inp = this[0], start = 0, end = 0; 
            if(!isNaN(inp.selectionStart)) 
            { 
            start = inp.selectionStart; 
            end = inp.selectionEnd; 
            } 
            else if( inp.createTextRange ) 
            { 
            var inpTxtLen = inp.value.length, jqueryTxtLen = this.val().length; 
            var inpRange = inp.createTextRange(), collapsedRange = inp.createTextRange(); 

            inpRange.moveToBookmark(document.selection.createRange().getBookmark()); 
            collapsedRange.collapse(false); 

            start = inpRange.compareEndPoints('StartToEnd', collapsedRange) > -1 ? jqueryTxtLen : inpRange.moveStart('character', -inpTxtLen); 
            end = inpRange.compareEndPoints('EndToEnd', collapsedRange) > -1 ? jqueryTxtLen : inpRange.moveEnd('character', -inpTxtLen); 
            } 
            return {start: Math.abs(start), end: Math.abs(end)}; 

            }, 
            // Usage: $('#txtArea').replaceCaretSelection({start: startIndex, end: endIndex, text: 'text to replace with', insPos: 'before|after|select'}) 
            // Options     start: start index of the text to be replaced 
            //               end: end index of the text to be replaced 
            //              text: text to replace the selection with 
            //            insPos: indicates whether to place the caret 'before' or 'after' the replacement text, 'select' will select the replacement text 

            replaceCaretSelection: function(options) 
            { 
            var pos = this.caretSelection(); 
            this.val( this.val().substring(0,pos.start) + options.text + this.val().substring(pos.end) ); 
            if(options.insPos == 'before') 
            { 
            this.caretSelection({start: pos.start, end: pos.start}); 
            } 
            else if( options.insPos == 'after' ) 
            { 
            this.caretSelection({start: pos.start + options.text.length, end: pos.start + options.text.length}); 
            } 
            else if( options.insPos == 'select' ) 
            { 
            this.caretSelection({start: pos.start, end: pos.start + options.text.length}); 
            } 
            } 
        });