【问题标题】:Is there a version of this code supported by IE11?IE11 是否支持此代码的版本?
【发布时间】:2015-07-30 21:31:58
【问题描述】:

我只是想知道如何让这段代码在 IE11 上运行以返回文本字段中的当前光标位置:

getCursorPosition: function() {
  var s, e, r;
  if(this.inputTextElement.createTextRange){
     r = document.selection.createRange().duplicate();
     r.moveEnd('character', this.inputTextElement.value.length);
     if(r.text === ''){
        s = this.inputTextElement.value.length;
     } else {
        s = this.inputTextElement.value.lastIndexOf(r.text);
     }
     r = document.selection.createRange().duplicate();
     r.moveStart('character', -this.inputTextElement.value.length);
     e = r.text.length;
  } else {
     s = this.inputTextElement.selectionStart;
     e = this.inputTextElement.selectionEnd;
  }
  return this.CursorPosition(s, e, r, this.inputTextElement.value);
},

【问题讨论】:

  • 你有没有弄清楚它的哪一部分不起作用?
  • IE11运行第一个if语句,然后在document.selection.createRange().duplicate()处返回错误; IE11 不支持 document.selection,但我不知道如何使用 window.getSelection();

标签: javascript internet-explorer-11


【解决方案1】:

我发现了问题。显然 IE11 不支持第一部分(第一个 if 语句),但在 if 语句上返回 true。我的代码现在专门检查 IE11 并确保您没有在第一个 if 语句中使用 IE11。第二个 if 语句运行良好。

【讨论】:

    【解决方案2】:

    试试这个:

        getCursorPosition: function () {
        var s, e, r;
        if (this.inputTextElement.getSelection) {
            r = document.getSelection();
            if (r.text === '') {
                s = this.inputTextElement.value.length;
            } else {
                s = this.inputTextElement.value.lastIndexOf(r.text);
            }
            e = r.focusOffset.toString();
        } else {
            s = this.inputTextElement.selectionStart;
            e = this.inputTextElement.selectionEnd;
        }
        return this.CursorPosition(s, e, r, this.inputTextElement.value);
    },
    

    下面的函数也改一下

    moveCursorToPosition : function(keycode, cursorPosition) {
        var p = (!keycode || (keycode && keycode.isBackspace ))? cursorPosition.start: cursorPosition.start + 1;
        if (this.inputTextElement.getSelection) {
            cursorPosition.range.move('character', p);
            cursorPosition.range.select();
        } else {
            this.inputTextElement.selectionStart = p;
            this.inputTextElement.selectionEnd = p;
        }
    },
    

    【讨论】:

      猜你喜欢
      • 2019-11-23
      • 2016-10-22
      • 1970-01-01
      • 2020-08-24
      • 1970-01-01
      • 2014-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多