Is there a way to get the offset of the selected text in the input field in IE?

In Firefox, you can simply call:

myInputTextField.selectionStart or myInputTextField.selectionEnd

to get the first and last indices of the selected text in the input field.

In IE, I know that you can call document.selection.createRange () to play around with a little selection. However, for my life I did not find a value that represents the offset of the character within the selection.

Am I missing something? Is there a way to get the same value in IE?

Thanks!

Alex

+3
source share
2 answers

,

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
        }
}
+5
  getSelectionOffset : function(argObject) {
   if (typeof(argObject.contentWindow.getSelection) != 'undefined') { //Moz
    return {
     start: argObject.contentWindow.getSelection().getRangeAt(0).selectionStart,
     end: argObject.contentWindow.getSelection().getRangeAt(0).selectionEnd
    }
   }
   if (document.selection && document.selection.createRange) { //IE
    var allText = argObject.contentWindow.document.selection.createRange().parentElement().innerText;
    var selText = argObject.contentWindow.document.selection.createRange().text;
    return {
     start: allText.indexOf(selText),
     end: allText.indexOf(selText) + selText.length 
    }
   }
  }
0

Source: https://habr.com/ru/post/1703781/


All Articles