当编辑值时,IE11将光标移动到输入的开头 [英] IE11 moves cursor to beginning of input when editing value

查看:150
本文介绍了当编辑值时,IE11将光标移动到输入的开头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个项目上有一个非常奇怪的问题。长话短说,我有输入字段记录利率,因此%附加在模糊上并在焦点上删除。它适用于除IE11之外的所有浏览器。由于某种原因,它将光标移动到输入的开头,这对于人们快速浏览并快速输入值很烦人。

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" />

同样,这只发生在IE11中(在旧版本的IE中工作正常)。有没有人遇到过这个问题?重新分配值后,我尝试再次强制关注焦点,但这并没有解决问题。任何提示都表示赞赏。

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.

推荐答案

您可以尝试在追加/删除%<时手动设置插入位置/ code> mark,使用这两个函数(非常通用,如果你需要在其他时间为所有浏览器设置插入位置,那么它们适用于每个浏览器):

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();
    }
  }
}

仅在使用时调用它们IE11 :)此外,如果你想,你可以使这些功能更具体,删除FF的部分:)

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

这篇关于当编辑值时,IE11将光标移动到输入的开头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆