在javascript replace中停止光标跳转到输入字段的结尾

Pet*_*y B 36 javascript replace

我正在使用正则表达式从javascript中的文本输入区域中删除无效字符(在IE中运行).我在每个keyup事件上运行replace函数.但是,这会使光标在每次按键后跳转到文本框的末尾,这使得无法进行内联编辑.

这是它的实际应用:

http://jsbin.com/ifufuv/2

有谁知道如何使它,所以光标不会跳转到输入框的末尾?

Jos*_*ier 24

除了gilly3的回答之外,我认为有人可能会发现查看实际的代码片段很有用.

在下面的示例中,在JavaScript字符串操作之前selectionStartinput元素中检索属性.然后在操作之后将其selectionStart设置回初始位置.

根据您要实现的目标,您还可以selectionEnd代替selectionStart并设置范围:setSelectionRange(start, end).

document.getElementById('target').addEventListener('input', function (e) {
  var target = e.target,
      position = target.selectionStart; // Capture initial position
  
  target.value = target.value.replace(/\s/g, '');  // This triggers the cursor to move.
  
  target.selectionEnd = position;    // Set the cursor back to the initial position.
});
Run Code Online (Sandbox Code Playgroud)
<p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p>
<input type="text" id="target" />
Run Code Online (Sandbox Code Playgroud)


gil*_*ly3 15

您必须手动将光标放回原点.对于IE9,设置.selectionStart.selectionEnd(或使用.setSelectionRange(start, end)).对于IE8及更早版本,请使用.createTextRange()和调用.moveStart()文本范围.

  • @Mike:W3Schools并不值得像你这样的人为他们推广他们的网站.看看http://w3fools.com - w3s上的大量信息是错误的,或者为开发人员推广不良做法.网上有更好的资源,比如http://quirksmode.org或http://developer.mozilla.org. (8认同)
  • W3Schools有一个关于如何使用onkeypress取消键的一个很好的例子(在他们的例子中,它取消了数字,你似乎有足够的能力修改正则表达式来取出你不想要的字符).http://www.w3schools.com/jsref/event_onkeypress.asp (3认同)
  • 有关此基本技术的实现,请参见http://stackoverflow.com/questions/3286595/update-textarea-value-but-keep-cursor-position/3288215#3288215. (2认同)