小编典典

是否有Internet Explorer批准的selectionStart和selectionEnd替代品?

javascript

找出在实际浏览器中选择的内容非常简单:

var range = {
  start: textbox.selectionStart,
  end: textbox.selectionEnd
}

但是IE和往常一样不懂。跨浏览器的最佳方法是什么?


阅读 324

收藏
2020-05-01

共1个答案

小编典典

我将再次发布此函数,以查看该问题是否与另一个问题相关联。

以下将在所有浏览器中完成工作,并处理所有新行问题,而不会严重影响性能。我经过一番折腾之后才来到这里,现在我很确信这是最好的功能。

更新

此函数确实假定textarea / input具有焦点,因此您可能需要在调用textarea的focus()方法之前先对其进行调用。

function getInputSelection(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_input");
el.focus();
var sel = getInputSelection(el);
alert(sel.start + ", " + sel.end);
2020-05-01