Pet*_*y B 36 javascript replace
我正在使用正则表达式从javascript中的文本输入区域中删除无效字符(在IE中运行).我在每个keyup事件上运行replace函数.但是,这会使光标在每次按键后跳转到文本框的末尾,这使得无法进行内联编辑.
这是它的实际应用:
有谁知道如何使它,所以光标不会跳转到输入框的末尾?
Jos*_*ier 24
除了gilly3的回答之外,我认为有人可能会发现查看实际的代码片段很有用.
在下面的示例中,在JavaScript字符串操作之前selectionStart从input元素中检索属性.然后在操作之后将其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()文本范围.