有没有办法在IE的输入框中获取所选文本的偏移量?

Ale*_*lex 3 html javascript internet-explorer web-applications

在Firefox中,您只需调用:

myInputTextField.selectionStart或myInputTextField.selectionEnd

获取输入框中所选文本的第一个和最后一个索引.

在IE中,我知道你可以调用document.selection.createRange()来调整选择.然而,对于我的生活,我没有找到任何代表选择中的字符偏移的值.

我错过了什么吗?有没有办法在IE中获得相同的价值?

谢谢!

亚历克斯

Dan*_*ant 5

从直接引用之前的响应,以一个非常类似的问题,将让你一个选择的范围:

function getSelection(inputBox) {
        if ("selectionStart" in inputBox) {
                return {
                        start: inputBox.selectionStart,
                        end: inputBox.selectionEnd
                }
        }

        //and now, the blinkered IE way
        var bookmark = document.selection.createRange().getBookmark()
        var selection = inputBox.createTextRange()
        selection.moveToBookmark(bookmark)

        var before = inputBox.createTextRange()
        before.collapse(true)
        before.setEndPoint("EndToStart", selection)

        var beforeLength = before.text.length
        var selLength = selection.text.length

        return {
                start: beforeLength,
                end: beforeLength + selLength
        }
}
Run Code Online (Sandbox Code Playgroud)