IE11 moves cursor to beginning of input when editing value

这一生的挚爱 提交于 2019-12-10 19:15:22

问题


I have a really odd problem on a project. Long Story Short, I have input fields that record interest rate, so a % is appended on blur and removed on focus. It works fine on every browser except for IE11. For some reason, it moves the cursor to the beginning of the input, which is annoying for people tabbing through and typing in values quickly.

Here is a simplified example in:

$('#test').val('default');

$('#test').focus(function() {
    var value = $(this).val().slice(0, -1);
    $(this).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />

Again, this only happens in IE11 (works fine in older versions of IE). Has anyone run into this issue before? I tried forcing focus again after the value is reassigned, but that didn't solve the issue. Any tips are appreciated.


回答1:


You could try to set caret position manually when appending/removing % mark, using those two functions (those are pretty generic and should work for every browser if you need setting caret positions for all browsers some other time):

function getCaretPosition(element) {
  var caretPos = 0;
  if (element.type === 'text' || element.type === 'tel') {
    if (document.selection) { // IE Support
      element.focus();
      var Sel = document.selection.createRange();
      Sel.moveStart('character', -element.value.length);
      caretPos = Sel.text.length;
    } else if (element.selectionStart || element.selectionStart === '0') {// Firefox support
      caretPos = element.selectionStart;
    }
  }

  return caretPos;
}

function setCaretPosition(element, position) {
  if (element.type === 'text' || element.type === 'tel') {
    if (element.setSelectionRange) {
      element.focus();
      element.setSelectionRange(position, position);
    } else if (element.createTextRange) {
      var range = element.createTextRange();
      range.collapse(true);
      range.moveEnd('character', position);
      range.moveStart('character', position);
      range.select();
    }
  }
}

And call them only when using IE11 :) Also, if you want, you could make those functions more specific, removing parts for FF :)



来源:https://stackoverflow.com/questions/31322576/ie11-moves-cursor-to-beginning-of-input-when-editing-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!