[英]Stop cursor from jumping to end of input field in javascript replace
我正在使用正则表达式从javascript中的文本输入区域中删除无效字符(在IE中运行)。 我在每个keyup事件上运行replace函数。 但是,这会使光标在每次按键后跳转到文本框的末尾,这使得无法进行内联编辑。
这是它的实际应用:
有谁知道如何使它,所以光标不会跳转到输入框的末尾?
除了gilly3的回答之外 ,我认为有人可能会发现查看实际的代码片段很有用。
在下面的示例中,在JavaScript字符串操作之前从input
元素中检索selectionStart
属性。 然后在操作之后将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. });
<p>The method <code>.replace()</code> will move the cursor's position, but you won't notice this.</p> <input type="text" id="target" />
您必须手动将光标放回原点。 对于IE9,设置.selectionStart
和.selectionEnd
(或使用.setSelectionRange(start, end)
)。 对于IE8及更早版本,请使用.createTextRange()
并在文本范围内调用.moveStart()
。
我遇到了同样的问题,我发现https://www.sitepoint.com/6-jquery-cursor-functions/有解决方案。 这里有6种方法可以让你在输入/ textarea中获取/设置光标位置。 我相信这也适用于内容可编辑字段!
这非常有用,因为该错误仅针对IE和Windows 7组合显示。
这是我的Before代码
$body.on('input paste','.replace-special-chars',function () {
let coma = /‚/g;
let doubleQuotes = /[“”]/g;
let singleQuotes = /[‘’]/g;
$(this).val($(this).val().replace(doubleQuotes,'"'));
$(this).val($(this).val().replace(coma,','));
$(this).val($(this).val().replace(singleQuotes,"'"));
$(this).val($(this).val().replace(/[^\x00-\xff]/g, '- '));
});
和我的后代码利用我在上面提到的网站上找到的jquery方法
$body.on('input paste','.replace-special-chars',function () {
let position = $(this).getCursorPosition();
let coma = /‚/g;
let doubleQuotes = /[“”]/g;
let singleQuotes = /[‘’]/g;
$(this).val($(this).val().replace(doubleQuotes,'"'));
$(this).val($(this).val().replace(coma,','));
$(this).val($(this).val().replace(singleQuotes,"'"));
$(this).val($(this).val().replace(/[^\x00-\xff]/g, '- '));
$(this).setCursorPosition(position);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.